security-basecamp for 0.9.2 is merged in master brach.
Change-Id: Ia5cd2710a688d3e631009ed03f7e5eb97aba5d24
Signed-off-by: Sachin Agrawal <sachin.agrawal@intel.com>
service/things-manager/build/linux/release
service/things-manager/build/linux/debug
service/things-manager/sdk/build/linux/
+
# Ignore any object files
*.o
+*.os
*.obj
+# Ignore libraries
+*.a
+*.so
# Ignore Eclipse workspace files
*.settings/
# Ignore CTags default data
tags
+
# Ignore dependencies folder, which should be generated
dependencies/
+dep/
#ignore Klocwork stuff
.kwlp/
extlibs/android/ndk/android-ndk-r10d
extlibs/android/sdk/android-sdk_r24.2
extlibs/boost/boost_1_58_0
+extlibs/tinycbor/tinycbor
*.tgz
*.zip
extlibs/arduino/arduino-1.5.8
build_common/arduino/extlibs/arduino/arduino-1.5.8
+extlibs/tinydtls/dtls-client
+extlibs/tinydtls/dtls-server
# Ignore editor (e.g. Emacs) backup and autosave files
*~
# Ignore byte-compiled Python scripts
*.pyc
+
+# Ignore Valgrind generated files.
+*.memcheck
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/
-
+CBOR serialization is provided by the tinycbor package,
+which is open source software, written by Thiago Macieira and is
+copyright by the Intel Corporation. The original software is available
+from
+ https://github.com/01org/tinycbor/
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/
-
-
command in this directory)
Install external libraries:
- $ sudo apt-get install libboost-dev libboost-program-options-dev libexpat1-dev libboost-thread-dev uuid-dev
+ $ sudo apt-get install libboost-dev libboost-program-options-dev libexpat1-dev libboost-thread-dev uuid-dev libssl-dev
Build release binaries:
$ scons
-(Note: C++ sdk requires cereal. Please follow the instruction in the build
-message to install cereal)
+(Note: C sdk requires tiny-cbor. Please follow the instruction in the build
+message to install tiny-cbor)
Build debug binaries:
$scons RELEASE=false
guide you to do that.)
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
+To build for tizen platform tiny-cbor library is needed.
+Please download tiny-cbor if it is not present in extlibs/tiny-cbor folder
+by doing the following:
+ $ git clone https://github.com/01org/tinycbor.git extlibs/tinycbor/tinycbor
* 3. External libraries
1. Build IoTivity project for Linux
$ cd <top directory of the project>
- $ sudo apt-get install libboost-dev libexpat1-dev libboost-thread-dev
+ $ sudo apt-get install libboost-dev libexpat1-dev libboost-thread-dev libssl-dev
$ scons
2. Build IoTivity project for Android
\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
+6. Verify that 7 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
\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
+9. Verify that 7 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
<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
JniEntityHandler.cpp \\r
JniOnResourceFoundListener.cpp \\r
JniOnDeviceInfoListener.cpp \\r
+ JniOnPlatformInfoListener.cpp \\r
JniOnPresenceListener.cpp \\r
JniOnGetListener.cpp \\r
JniOnPutListener.cpp \\r
ThrowOcException(JNI_EXCEPTION, "OnDeviceInfoListenet not found");\r
}\r
deviceInfoMapLock.unlock();\r
+}
+
+JniOnPlatformInfoListener* AddOnPlatformInfoListener(JNIEnv* env, jobject jListener)
+{
+ JniOnPlatformInfoListener *onPlatformInfoListener = NULL;
+
+ platformInfoMapLock.lock();
+
+ for (auto it = onPlatformInfoListenerMap.begin(); it != onPlatformInfoListenerMap.end(); ++it)
+ {
+ if (env->IsSameObject(jListener, it->first))
+ {
+ auto refPair = it->second;
+ onPlatformInfoListener = refPair.first;
+ refPair.second++;
+ it->second = refPair;
+ onPlatformInfoListenerMap.insert(*it);
+ LOGD("OnPlatformInfoListener: ref. count incremented");
+ break;
+ }
+ }
+
+ if (!onPlatformInfoListener)
+ {
+ onPlatformInfoListener = new JniOnPlatformInfoListener(env, jListener, RemoveOnPlatformInfoListener);
+ jobject jgListener = env->NewGlobalRef(jListener);
+
+ onPlatformInfoListenerMap.insert(std::pair < jobject, std::pair < JniOnPlatformInfoListener*,
+ int >> (jgListener, std::pair<JniOnPlatformInfoListener*, int>(onPlatformInfoListener, 1)));
+ LOGI("OnPlatformInfoListener: new listener");
+ }
+
+ platformInfoMapLock.unlock();
+ return onPlatformInfoListener;
+}
+
+void RemoveOnPlatformInfoListener(JNIEnv* env, jobject jListener)
+{
+ platformInfoMapLock.lock();
+ bool isFound = false;
+ for (auto it = onPlatformInfoListenerMap.begin(); it != onPlatformInfoListenerMap.end(); ++it)
+ {
+ if (env->IsSameObject(jListener, it->first))
+ {
+ auto refPair = it->second;
+ if (refPair.second > 1)
+ {
+ refPair.second--;
+ it->second = refPair;
+ onPlatformInfoListenerMap.insert(*it);
+ LOGI("OnPlatformInfoListener: ref. count decremented");
+ }
+ else
+ {
+ env->DeleteGlobalRef(it->first);
+ JniOnPlatformInfoListener* listener = refPair.first;
+ delete listener;
+ onPlatformInfoListenerMap.erase(it);
+
+ LOGI("OnPlatformInfoListener removed");
+ }
+
+ isFound = true;
+ break;
+ }
+ }
+
+ if (!isFound)
+ {
+ ThrowOcException(JNI_EXCEPTION, "OnPlatformInfoListenet not found");
+ }
+ platformInfoMapLock.unlock();
}\r
\r
JniOnPresenceListener* AddOnPresenceListener(JNIEnv* env, jobject jListener)\r
/*\r
* Class: org_iotivity_base_OcPlatform\r
* Method: configure\r
-* Signature: (IILjava/lang/String;IILjava/lang/String;)V
+* 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,
if (OC_STACK_OK != result)\r
{\r
ThrowOcException(result, "Find device has failed");\r
+ }
+ }
+ catch (OCException& e)
+ {
+ LOGE("%s", e.reason().c_str());
+ ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ }
+}
+
+/*
+* Class: org_iotivity_base_OcPlatform
+* Method: getPlatformInfo0
+* Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnPlatformFoundListener;)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getPlatformInfo0
+(JNIEnv *env, jclass clazz, jstring jHost, jstring jResourceUri, jint jConnectivityType, jobject jListener)
+{
+ LOGD("OcPlatform_getPlatformInfo0");
+ std::string host;
+ if (jHost)
+ {
+ host = env->GetStringUTFChars(jHost, NULL);
+ }
+ std::string resourceUri;
+ if (jResourceUri)
+ {
+ resourceUri = env->GetStringUTFChars(jResourceUri, NULL);
+ }
+ if (!jListener)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "onPlatformFoundListener cannot be null");
+ return;
+ }
+ JniOnPlatformInfoListener *onPlatformInfoListener = AddOnPlatformInfoListener(env, jListener);
+
+ FindPlatformCallback findPlatformCallback = [onPlatformInfoListener](const OCRepresentation& ocRepresentation)
+ {
+ onPlatformInfoListener->foundPlatformCallback(ocRepresentation);
+ };
+
+ try
+ {
+ OCStackResult result = OCPlatform::getPlatformInfo(
+ host,
+ resourceUri,
+ JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),
+ findPlatformCallback);
+
+ if (OC_STACK_OK != result)
+ {
+ ThrowOcException(result, "Find platform has failed");
+ }
+ }
+ catch (OCException& e)
+ {
+ LOGE("%s", e.reason().c_str());
+ ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ }
+}
+
+/*
+* Class: org_iotivity_base_OcPlatform
+* Method: getPlatformInfo1
+* Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnPlatformFoundListener;I)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getPlatformInfo1
+(JNIEnv *env, jclass clazz, jstring jHost, jstring jResourceUri, jint jConnectivityType, jobject jListener, jint jQoS)
+{
+ LOGD("OcPlatform_getPlatformInfo1");
+ std::string host;
+ if (jHost)
+ {
+ host = env->GetStringUTFChars(jHost, NULL);
+ }
+ std::string resourceUri;
+ if (jResourceUri)
+ {
+ resourceUri = env->GetStringUTFChars(jResourceUri, NULL);
+ }
+ if (!jListener)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "onPlatformFoundListener cannot be null");
+ return;
+ }
+ JniOnDeviceInfoListener *onDeviceInfoListener = AddOnDeviceInfoListener(env, jListener);
+
+ FindDeviceCallback findDeviceCallback = [onDeviceInfoListener](const OCRepresentation& ocRepresentation)
+ {
+ onDeviceInfoListener->foundDeviceCallback(ocRepresentation);
+ };
+
+ try
+ {
+ OCStackResult result = OCPlatform::getPlatformInfo(
+ host,
+ resourceUri,
+ JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),
+ findDeviceCallback,
+ JniUtils::getQOS(env, static_cast<int>(jQoS)));
+
+ if (OC_STACK_OK != result)
+ {
+ ThrowOcException(result, "Find platform has failed");
}\r
}\r
catch (OCException& e)\r
}\r
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, jResource);\r
if (!resource) return nullptr;\r
-\r
+ LOGD("OcPlatform_registerResource1");
OCResourceHandle resourceHandle;\r
try\r
{\r
+ LOGD("OcPlatform_registerResource2");
OCStackResult result = OCPlatform::registerResource(\r
resourceHandle,\r
resource->getOCResource());\r
+ LOGD("OcPlatform_registerResource3");
\r
if (OC_STACK_OK != result)\r
{\r
ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
return nullptr;\r
}\r
-\r
+ LOGD("OcPlatform_registerResource4");
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
+ LOGD("OcPlatform_registerResource5");
if (!jResourceHandle)\r
{\r
LOGE("Failed to create OcResourceHandle");\r
\r
/*\r
* Class: org_iotivity_base_OcPlatform\r
+* Method: registerPlatformInfo0
+* 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;)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerPlatformInfo0
+(JNIEnv *env,
+jclass clazz,
+jstring jPlatformID,
+jstring jManufacturerName,
+jstring jManufacturerUrl,
+jstring jModelNumber,
+jstring jDateOfManufacture,
+jstring jPlatformVersion,
+jstring jOperatingSystemVersion,
+jstring jHardwareVersion,
+jstring jFirmwareVersion,
+jstring jSupportUrl,
+jstring jSystemTime)
+{
+ LOGI("OcPlatform_registerPlatformInfo");
+
+
+ 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 (jPlatformID)
+ {
+ platformID = env->GetStringUTFChars(jPlatformID, NULL);
+ }
+ if (jManufacturerName)
+ {
+ manufacturerName = env->GetStringUTFChars(jManufacturerName, NULL);
+ }
+ if (jManufacturerUrl)
+ {
+ manufacturerUrl = env->GetStringUTFChars(jManufacturerUrl, NULL);
+ }
+ if (jModelNumber)
+ {
+ modelNumber = env->GetStringUTFChars(jModelNumber, NULL);
+ }
+ if (jDateOfManufacture)
+ {
+ dateOfManufacture = env->GetStringUTFChars(jDateOfManufacture, NULL);
+ }
+ if (jPlatformVersion)
+ {
+ platformVersion = env->GetStringUTFChars(jPlatformVersion, NULL);
+ }
+ if (jOperatingSystemVersion)
+ {
+ operatingSystemVersion = env->GetStringUTFChars(jOperatingSystemVersion, NULL);
+ }
+ if (jHardwareVersion)
+ {
+ hardwareVersion = env->GetStringUTFChars(jHardwareVersion, NULL);
+ }
+ if (jFirmwareVersion)
+ {
+ firmwareVersion = env->GetStringUTFChars(jFirmwareVersion, NULL);
+ }
+ if (jSupportUrl)
+ {
+ supportUrl = env->GetStringUTFChars(jSupportUrl, NULL);
+ }
+ if (jSystemTime)
+ {
+ systemTime = env->GetStringUTFChars(jSystemTime, NULL);
+ }
+
+ OCPlatformInfo platformInfo;
+ try
+ {
+ 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);
+ }
+ catch (std::exception &e)
+ {
+ ThrowOcException(JNI_EXCEPTION, "Failed to construct platform info");
+ return;
+ }
+
+ // __android_log_print(ANDROID_LOG_INFO, "Rahul", "platformID = %s", platformID);
+ try
+ {
+ OCStackResult result = OCPlatform::registerPlatformInfo(platformInfo);
+
+ 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;
+
+ if (OC_STACK_OK != result)
+ {
+ ThrowOcException(result, "Failed to register platform info");
+ return;
+ }
+ }
+ catch (OCException& e)
+ {
+ LOGE("Error is due to %s", e.reason().c_str());
+ ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ }
+
+
+
+}
+
+/*
+* Class: org_iotivity_base_OcPlatform
* Method: unregisterResource0\r
* Signature: (Lorg/iotivity/base/OcResourceHandle;)V\r
*/\r
LOGE("Failed to create OcPresenceHandle");\r
delete jniPresenceHandle;\r
}\r
-\r
return jPresenceHandle;\r
}\r
\r
#include "JniOcStack.h"\r
#include "JniOnResourceFoundListener.h"\r
#include "JniOnDeviceInfoListener.h"\r
+#include "JniOnPlatformInfoListener.h"
#include "JniOnPresenceListener.h"\r
#include <mutex>\r
\r
JniOnDeviceInfoListener* AddOnDeviceInfoListener(JNIEnv* env, jobject jListener);\r
void RemoveOnDeviceInfoListener(JNIEnv* env, jobject jListener);\r
\r
+JniOnPlatformInfoListener* AddOnPlatformInfoListener(JNIEnv* env, jobject jListener);
+void RemoveOnPlatformInfoListener(JNIEnv* env, jobject jListener);
+
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<JniOnPlatformInfoListener*, int>> onPlatformInfoListenerMap;
std::map<jobject, std::pair<JniOnPresenceListener*, int>> onPresenceListenerMap;\r
\r
std::mutex resourceFoundMapLock;\r
std::mutex deviceInfoMapLock;\r
+std::mutex platformInfoMapLock;
std::mutex presenceMapLock;\r
\r
#ifdef __cplusplus\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);
+
+ /*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: getPlatformInfo0
+ * Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnPlatformFoundListener;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getPlatformInfo0
+ (JNIEnv *, jclass, jstring, jstring, jint, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: getPlatformInfo1
+ * Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnPlatformFoundListener;I)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getPlatformInfo1
(JNIEnv *, jclass, jstring, jstring, jint, jobject, jint);\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
+ * Signature: (Ljava/lang/String;)V
*/\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
+ (JNIEnv *, jclass, jstring);
+
+ /*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: registerPlatformInfo0
+ * 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;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerPlatformInfo0
+ (JNIEnv *, jclass, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring);
\r
/*\r
* Class: org_iotivity_base_OcPlatform\r
}\r
#endif\r
#endif\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
{\r
delete rep;\r
}\r
-}
\ No newline at end of file
+}\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
#ifdef __cplusplus\r
}\r
#endif\r
-#endif
\ No newline at end of file
+#endif
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // 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 "JniOnPlatformInfoListener.h"
+#include "JniOcRepresentation.h"
+
+JniOnPlatformInfoListener::JniOnPlatformInfoListener(JNIEnv *env, jobject jListener,
+ RemoveListenerCallback removeListenerCallback)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+ m_removeListenerCallback = removeListenerCallback;
+}
+
+JniOnPlatformInfoListener::~JniOnPlatformInfoListener()
+{
+ LOGI("~JniOnPlatformInfoListener");
+ if (m_jwListener)
+ {
+ jint ret;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (NULL == env) return;
+ env->DeleteWeakGlobalRef(m_jwListener);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation& ocRepresentation)
+{
+ jint ret;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (NULL == env) return;
+
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ LOGI("Java onPlatformInfoListener object is already destroyed, quiting");
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ OCRepresentation* rep = new OCRepresentation(ocRepresentation);
+ jlong handle = reinterpret_cast<jlong>(rep);
+ jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,
+ handle, true);
+ if (!jRepresentation)
+ {
+ delete rep;
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+ if (!clsL)
+ {
+ delete rep;
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+ jmethodID midL = env->GetMethodID(clsL, "onPlatformFound", "(Lorg/iotivity/base/OcRepresentation;)V");
+ if (!midL)
+ {
+ delete rep;
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ return;
+ }
+
+ env->CallVoidMethod(jListener, midL, jRepresentation);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Java exception is thrown");
+ delete rep;
+ checkExAndRemoveListener(env);
+ }
+
+ if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+}
+
+void JniOnPlatformInfoListener::checkExAndRemoveListener(JNIEnv* env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_removeListenerCallback(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_removeListenerCallback(env, m_jwListener);
+ }
+}
+
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // 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 "JniOcStack.h"
+
+#ifndef _Included_org_iotivity_base_OcPlatform_OnPlatformFoundListener
+#define _Included_org_iotivity_base_OcPlatform_OnPlatformFoundListener
+
+class JniOnPlatformInfoListener
+{
+public:
+ JniOnPlatformInfoListener(JNIEnv *env, jobject jListener, RemoveListenerCallback removeListener);
+ ~JniOnPlatformInfoListener();
+
+ void foundPlatformCallback(const OC::OCRepresentation& ocRepresentation);
+
+private:
+ jweak m_jwListener;
+ RemoveListenerCallback m_removeListenerCallback;
+ void checkExAndRemoveListener(JNIEnv* env);
+};
+
+#endif
Log.i(TAG, "Host: " + resource.getHost());
Log.i(TAG, "Server ID: " + resource.getServerId());
Log.i(TAG, "Connectivity Type: " + resource.getConnectivityType());
+ Log.i(TAG, "Connectivity Type: " + resource.getConnectivityFlags());
signal.countDown();
}
};
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
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);
- }
- }
+// TODO - this test fails currently
+// 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.CT_DEFAULT,
+// 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.CT_DEFAULT,
+// 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";
//client
OcPlatform.findResource(null,
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
}
}
+ public void testPlatformInfo() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal = new CountDownLatch(1);
+
+ OcPlatform.OnPlatformFoundListener platformFoundListener = new OcPlatform.OnPlatformFoundListener() {
+ @Override
+ public void onPlatformFound(OcRepresentation ocRepresentation) {
+ Log.i(TAG, "Platform Info Received: ");
+ Log.i(TAG, "URI: " + ocRepresentation.getUri());
+ signal.countDown();
+ }
+ };
+
+ OcPlatformInfo platformInfo = null;
+ try {
+ platformInfo = new OcPlatformInfo("myPlatformID", "myManuName", "myManuUrl");
+ } catch (OcException e) {
+ Log.e(TAG, "Could not construct platformInfo. " + e.getMessage());
+ assertTrue(false);
+ }
+
+ platformInfo.setModelNumber("myModelNumber");
+ platformInfo.setDateOfManufacture("myDateOfManufacture");
+ platformInfo.setPlatformVersion("myPlatformVersion");
+ platformInfo.setOperatingSystemVersion("myOperatingSystemVersion");
+ platformInfo.setHardwareVersion("myHardwareVersion");
+ platformInfo.setFirmwareVersion("myFirmwareVersion");
+ platformInfo.setSupportUrl("mySupportUrl");
+ platformInfo.setSystemTime("mySystemTime");
+
+ try {
+ //server
+
+ OcPlatform.registerPlatformInfo(platformInfo);
+
+ //client
+ OcPlatform.getPlatformInfo(
+ "",
+ OcPlatform.MULTICAST_PREFIX + "/oic/p",
+ OcConnectivityType.CT_DEFAULT,
+ platformFoundListener);
+
+ //wait for onPlatformFound event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage() + platformInfo.toString());
+ assertTrue(false);
+ }
+ }
+
// public void testRegisterDeviceInfoGetDeviceInfo() throws InterruptedException {
// final String resourceType = "unit.test.resource" + new Date().getTime();
// final CountDownLatch signal = new CountDownLatch(1);
// OcPlatform.getDeviceInfo(
// "",
// OcPlatform.MULTICAST_PREFIX + DEVICE_URI,
-// OcConnectivityType.IPV4,
+// OcConnectivityType.CT_DEFAULT,
// deviceFoundListener);
//
// //wait for onDeviceFound event
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener1);
//wait for onResourceFound event to find 3 registered resources
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener3);
//wait for onResourceFound event to find 1 collection resources
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener2);
//wait for onResourceFound event to find 2 resources
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener4);
//wait for onResourceFound event to find 3 registered resources
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener6);
//wait for onResourceFound event to find 1 collection resources
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener5);
//wait for onResourceFound event to find 1 collection resources
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType1,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType2,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
OcResource resourceProxy = OcPlatform.constructResourceObject(
resource.getHost(),
resource.getUri(),
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resource.isObservable(),
resource.getResourceTypes(),
resource.getResourceInterfaces());
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
//client
OcPlatform.findResource("",
OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
- OcConnectivityType.IPV4,
+ OcConnectivityType.CT_DEFAULT,
resourceFoundListener);
//wait for onResourceFound event
-/*\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
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+
+public enum ErrorCode {
+ /* Success status code - START HERE */
+ OK("OK", ""),
+ RESOURCE_CREATED("RESOURCE_CREATED", ""),
+ RESOURCE_DELETED("RESOURCE_DELETED", ""),
+ CONTINUE("CONTINUE", ""),
+ /* Success status code - END HERE */
+ /* Error status code - START HERE */
+ INVALID_URI("INVALID_URI", ""),
+ INVALID_QUERY("INVALID_QUERY", ""),
+ INVALID_IP("INVALID_IP", ""),
+ INVALID_PORT("INVALID_PORT", ""),
+ INVALID_CALLBACK("INVALID_CALLBACK", ""),
+ INVALID_METHOD("INVALID_METHOD", ""),
+ INVALID_PARAM("INVALID_PARAM", ""),
+ INVALID_OBSERVE_PARAM("INVALID_OBSERVE_PARAM", ""),
+ NO_MEMORY("NO_MEMORY", ""),
+ COMM_ERROR("COMM_ERROR", ""),
+ NOT_IMPL("NOTIMPL", ""),
+ NO_RESOURCE("NO_RESOURCE", "Resource not found"),
+ RESOURCE_ERROR("RESOURCE_ERROR", "Not supported method or interface"),
+ SLOW_RESOURCE("SLOW_RESOURCE", ""),
+ NO_OBSERVERS("NO_OBSERVERS", "Resource has no registered observers"),
+ OBSERVER_NOT_FOUND("OBSERVER_NOT_FOUND", ""),
+ PRESENCE_STOPPED("PRESENCE_STOPPED", ""),
+ PRESENCE_TIMEOUT("PRESENCE_TIMEOUT", ""),
+ PRESENCE_DO_NOT_HANDLE("PRESENCE_DO_NOT_HANDLE", ""),
+ VIRTUAL_DO_NOT_HANDLE("VIRTUAL_DO_NOT_HANDLE", ""),
+ INVALID_OPTION("INVALID_OPTION", ""),
+ MALFORMED_RESPONSE("MALFORMED_RESPONSE", "Remote reply contained malformed data"),
+ PERSISTENT_BUFFER_REQUIRED("PERSISTENT_BUFFER_REQUIRED", ""),
+ INVALID_REQUEST_HANDLE("INVALID_REQUEST_HANDLE", ""),
+ INVALID_DEVICE_INFO("INVALID_DEVICE_INFO", ""),
+ INVALID_PLATFORM_INFO_PLATFORMID("INVALID_PLATFORM_INFO_PLATFORMID",
+ "PlatformID cannot be null or empty"),
+ INVALID_PLATFORM_INFO_MANUFACTURER_NAME("INVALID_PLATFORM_INFO_MANUFACTURER_NAME",
+ "ManufacturerName cannot be null, empty or greater than " +
+ OcStackConfig.MAX_MANUFACTURER_NAME_LENGTH + " characters long"),
+ INVALID_PLATFORM_INFO_PLATFORMID_MANUFACTURER_URL("INVALID_PLATFORM_INFO_MANUFACTURER_URL",
+ "MANUFACTURER_URL cannot be null, empty or greater than " +
+ OcStackConfig.MAX_MANUFACTURER_URL_LENGTH + " characters long"),
+ ERROR("ERROR", "Generic error"),
+
+ JNI_EXCEPTION("JNI_EXCEPTION", "Generic Java binder error"),
+ JNI_NO_NATIVE_OBJECT("JNI_NO_NATIVE_OBJECT", ""),
+ JNI_INVALID_VALUE("JNI_INVALID_VALUE", ""),
+
+ INVALID_CLASS_CAST("INVALID_CLASS_CAST", ""),;
+
+ private String error;
+ private String description;
+
+ private ErrorCode(String error, String description) {
+ this.error = error;
+ this.description = description;
+ }
+
+ public String getError() {
+ return error;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public static ErrorCode get(String errorCode) {
+ for (ErrorCode eCode : ErrorCode.values()) {
+ if (eCode.getError().equals(errorCode)) {
+ return eCode;
+ }
+ }
+ throw new IllegalArgumentException("Unexpected ErrorCode value");
+ }
+
+ @Override
+ public String toString() {
+ return error + (description.isEmpty() ? "" : " : " + description);
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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 java.security.InvalidParameterException;
+public enum OcConnectivityFlags {
+ OC_DEFAULT_FLAGS (0),
+ // Insecure transport is the default (subject to change)
+ OC_FLAG_SECURE (1 << 4), // secure the transport path
+
+ // IPv4 & IPv6 autoselection is the default
+ OC_IP_USE_V6 (1 << 5), // IP adapter only
+ OC_IP_USE_V4 (1 << 6), // IP adapter only
+
+ // Link-Local multicast is the default multicast scope for IPv6.
+ // These are placed here to correspond to the IPv6 address bits.
+ OC_SCOPE_INTERFACE (0x1), // IPv6 Interface-Local scope (loopback)
+ OC_SCOPE_LINK (0x2), // IPv6 Link-Local scope (default)
+ OC_SCOPE_REALM (0x3), // IPv6 Realm-Local scope
+ OC_SCOPE_ADMIN (0x4), // IPv6 Admin-Local scope
+ OC_SCOPE_SITE (0x5), // IPv6 Site-Local scope
+ OC_SCOPE_ORG (0x8), // IPv6 Organization-Local scope
+ OC_SCOPE_GLOBAL (0xE), // IPv6 Global scope
+ ;
+ private int value;
+
+ private OcConnectivityFlags(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return this.value;
+ }
+
+ public static OcConnectivityFlags get(int val) {
+ for (OcConnectivityType v : OcConnectivityType.values()) {
+ for (OcConnectivityFlags f : OcConnectivityFlags.values()) {
+ int value = v.getValue() + f.getValue();
+ if (value == val)
+ return f;
+ }
+ }
+ throw new InvalidParameterException("Unexpected OcConnectivityFlags value:" + val);
+ }
+}
\ No newline at end of file
-/*\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
+/*
+ * //******************************************************************
+ * //
+ * // 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 java.security.InvalidParameterException;
+
+public enum OcConnectivityType {
+ CT_DEFAULT (0),
+ CT_ADAPTER_IP (1 << 16),
+ CT_ADAPTER_GATT_BTLE (1 << 17),
+ CT_ADAPTER_RFCOMM_BTEDR (1 << 18),
+ ;
+
+ private int value;
+
+ private OcConnectivityType(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return this.value;
+ }
+
+ public static OcConnectivityType get(int val) {
+ // val is a combination of OcConnectivityType and OcConnectivityFlags
+ for (OcConnectivityType v : OcConnectivityType.values()) {
+ for (OcConnectivityFlags f : OcConnectivityFlags.values()) {
+ int value = v.getValue() + f.getValue();
+ if (value == val)
+ return v;
+ }
+ }
+ throw new InvalidParameterException("Unexpected OcConnectivityType value:" + val);
+ }
+}
String deviceUri,\r
int connectivityType,\r
OnDeviceFoundListener onDeviceFoundListener,\r
+ int qualityOfService) throws OcException;
+
+ /**
+ * API for Platform Discovery
+ *
+ * @param host Host IP Address. If null or empty, Multicast is performed.
+ * @param platformUri Uri containing address to the platform
+ * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
+ * IPV6, ALL
+ * @param onPlatformFoundListener Handles events, success states and failure states.
+ * @throws OcException
+ */
+
+ public static void getPlatformInfo(
+ String host,
+ String platformUri,
+ OcConnectivityType connectivityType,
+ OnPlatformFoundListener onPlatformFoundListener) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.getPlatformInfo0(
+ host,
+ platformUri,
+ connectivityType.getValue(),
+ onPlatformFoundListener
+ );
+ }
+
+ private static native void getPlatformInfo0(
+ String host,
+ String platformUri,
+ int connectivityType,
+ OnPlatformFoundListener onPlatformInfoFoundListener) throws OcException;
+
+ /**
+ * API for Platform Discovery
+ *
+ * @param host Host IP Address. If null or empty, Multicast is performed.
+ * @param platformUri Uri containing address to the platform
+ * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
+ * IPV6, ALL
+ * @param onPlatformFoundListener Handles events, success states and failure states.
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+
+ public static void getPlatformInfo(
+ String host,
+ String platformUri,
+ OcConnectivityType connectivityType,
+ OnPlatformFoundListener onPlatformFoundListener,
+ QualityOfService qualityOfService) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.getPlatformInfo1(
+ host,
+ platformUri,
+ connectivityType.getValue(),
+ onPlatformFoundListener,
+ qualityOfService.getValue()
+ );
+ }
+
+ private static native void getPlatformInfo1(
+ String host,
+ String platformUri,
+ int connectivityType,
+ OnPlatformFoundListener onPlatformFoundListener,
int qualityOfService) throws OcException;\r
\r
/**\r
) throws OcException;\r
\r
/**\r
+ * Register Platform Info
+ *
+ * @param ocPlatformInfo object containing all the platform specific information
+ * @throws OcException
+ */
+ public static void registerPlatformInfo(
+ OcPlatformInfo ocPlatformInfo) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.registerPlatformInfo0(
+ ocPlatformInfo.getPlatformID(),
+ ocPlatformInfo.getManufacturerName(),
+ ocPlatformInfo.getManufacturerUrl(),
+ ocPlatformInfo.getModelNumber(),
+ ocPlatformInfo.getDateOfManufacture(),
+ ocPlatformInfo.getPlatformVersion(),
+ ocPlatformInfo.getOperatingSystemVersion(),
+ ocPlatformInfo.getHardwareVersion(),
+ ocPlatformInfo.getFirmwareVersion(),
+ ocPlatformInfo.getSupportUrl(),
+ ocPlatformInfo.getSystemTime()
+ );
+ }
+
+ private static native void registerPlatformInfo0(
+ String platformId, String manufacturerName, String manufacturerUrl,
+ String modelNumber, String dateOfManufacture, String platformVersion,
+ String operatingSystemVersion, String hardwareVersion, String firmwareVersion,
+ String supportUrl, String systemTime
+ ) throws OcException;
+
+ /**
* 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
*/\r
public interface OnDeviceFoundListener {\r
public void onDeviceFound(OcRepresentation ocRepresentation);\r
+ }
+
+ /**
+ * An OnPlatformFoundListener can be registered via the OcPlatform.getPlatformInfo call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnPlatformFoundListener {
+ public void onPlatformFound(OcRepresentation ocRepresentation);
}\r
\r
/**\r
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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 java.lang.Error;
+
+public class OcPlatformInfo {
+
+ private String platformID;
+ private String manufacturerName;
+ private String manufacturerUrl;
+ private String modelNumber;
+ private String dateOfManufacture;
+ private String platformVersion;
+ private String operatingSystemVersion;
+ private String hardwareVersion;
+ private String firmwareVersion;
+ private String supportUrl;
+ private String systemTime;
+
+ // construct OcPlatformInfo with mandatory fields which cannot be null
+ // manufacturerName cannot be > 16 chars
+ // manufacturerUrl cannot be > 32 chars
+ protected OcPlatformInfo(String platformID, String manufacturerName,
+ String manufacturerUrl) throws OcException {
+ ErrorCode result = validatePlatformInfo(platformID, manufacturerName, manufacturerUrl);
+ if (ErrorCode.OK == result) {
+ this.platformID = platformID;
+ this.manufacturerName = manufacturerName;
+ this.manufacturerUrl = manufacturerUrl;
+ } else {
+ throw new OcException(result, result.getDescription());
+ }
+ }
+
+ public ErrorCode validatePlatformInfo(String platformID, String manufacturerName,
+ String manufacturerUrl) {
+ // checks to see if the mandatory fields have non-null values or not
+ if (platformID == null || platformID.isEmpty()) return ErrorCode.INVALID_PLATFORM_INFO_PLATFORMID;
+ if (manufacturerName == null || manufacturerName.isEmpty() ||
+ manufacturerName.length() > OcStackConfig.MAX_MANUFACTURER_NAME_LENGTH)
+ return ErrorCode.INVALID_PLATFORM_INFO_MANUFACTURER_NAME;
+ if (manufacturerUrl == null || manufacturerUrl.isEmpty() ||
+ manufacturerUrl.length() > OcStackConfig.MAX_MANUFACTURER_URL_LENGTH)
+ return ErrorCode.INVALID_PLATFORM_INFO_PLATFORMID_MANUFACTURER_URL;
+ return ErrorCode.OK;
+ }
+
+ public String getPlatformID() {
+ return platformID;
+ }
+
+ public void setPlatformID(String platformID) {
+ this.platformID = platformID;
+ }
+
+ public String getManufacturerName() {
+ return manufacturerName;
+ }
+
+ public void setManufacturerName(String manufacturerName) {
+ this.manufacturerName = manufacturerName;
+ }
+
+ public String getManufacturerUrl() {
+ return manufacturerUrl;
+ }
+
+ public void setManufacturerUrl(String manufacturerUrl) {
+ this.manufacturerUrl = manufacturerUrl;
+ }
+
+ public String getModelNumber() {
+ return modelNumber;
+ }
+
+ public void setModelNumber(String modelNumber) {
+ this.modelNumber = modelNumber;
+ }
+
+ public String getDateOfManufacture() {
+ return dateOfManufacture;
+ }
+
+ public void setDateOfManufacture(String dateOfManufacture) {
+ this.dateOfManufacture = dateOfManufacture;
+ }
+
+ public String getPlatformVersion() {
+ return platformVersion;
+ }
+
+ public void setPlatformVersion(String platformVersion) {
+ this.platformVersion = platformVersion;
+ }
+
+ public String getOperatingSystemVersion() {
+ return operatingSystemVersion;
+ }
+
+ public void setOperatingSystemVersion(String operatingSystemVersion) {
+ this.operatingSystemVersion = operatingSystemVersion;
+ }
+
+ public String getHardwareVersion() {
+ return hardwareVersion;
+ }
+
+ public void setHardwareVersion(String hardwareVersion) {
+ this.hardwareVersion = hardwareVersion;
+ }
+
+ public String getFirmwareVersion() {
+ return firmwareVersion;
+ }
+
+ public void setFirmwareVersion(String firmwareVersion) {
+ this.firmwareVersion = firmwareVersion;
+ }
+
+ public String getSupportUrl() {
+ return supportUrl;
+ }
+
+ public void setSupportUrl(String supportUrl) {
+ this.supportUrl = supportUrl;
+ }
+
+ public String getSystemTime() {
+ return systemTime;
+ }
+
+ public void setSystemTime(String systemTime) {
+ this.systemTime = systemTime;
+ }
+}
-/*\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
+/*
+ * //******************************************************************
+ * //
+ * // 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 java.util.List;
+import java.util.Map;
+
+/**
+ * OcResource represents an OC resource. A resource could be a light controller, temperature sensor,
+ * smoke detector, etc. A resource comes with a well-defined contract or interface onto which you
+ * can perform different operations, such as turning on the light, getting the current temperature
+ * or subscribing for event notifications from the smoke detector. A resource can be composed of
+ * one or more resources.
+ */
+public class OcResource {
+
+ private OcResource(long nativeHandle) {
+ this.mNativeHandle = nativeHandle;
+ }
+
+ /**
+ * Method to get the attributes of a resource.
+ *
+ * @param queryParamsMap map which can have the query parameter name and value
+ * @param onGetListener The event handler will be invoked with a map of attribute name and
+ * values. The event handler will also have the result from this Get
+ * operation This will have error codes
+ * @throws OcException
+ */
+ public native void get(Map<String, String> queryParamsMap,
+ OnGetListener onGetListener) throws OcException;
+
+ /**
+ * Method to get the attributes of a resource.
+ *
+ * @param queryParamsMap map which can have the query parameter name and value
+ * @param onGetListener The event handler will be invoked with a map of attribute name and
+ * values. The event handler will also have the result from this Get
+ * operation This will have error codes
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+ public void get(Map<String, String> queryParamsMap,
+ OnGetListener onGetListener,
+ QualityOfService qualityOfService) throws OcException {
+ this.get1(queryParamsMap, onGetListener, qualityOfService.getValue());
+ }
+
+ private native void get1(Map<String, String> queryParamsMap,
+ OnGetListener onGetListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * Method to get the attributes of a resource.
+ *
+ * @param resourceType resourceType of the resource to operate on
+ * @param resourceInterface interface type of the resource to operate on
+ * @param queryParamsMap map which can have the query parameter name and value
+ * @param onGetListener The event handler will be invoked with a map of attribute name and
+ * values. The event handler will also have the result from this Get
+ * operation This will have error codes
+ * @throws OcException
+ */
+ public void get(String resourceType,
+ String resourceInterface,
+ Map<String, String> queryParamsMap,
+ OnGetListener onGetListener) throws OcException {
+ this.get2(
+ resourceType,
+ resourceInterface,
+ queryParamsMap,
+ onGetListener);
+ }
+
+ private native void get2(String resourceType,
+ String resourceInterface,
+ Map<String, String> queryParamsMap,
+ OnGetListener onGetListener) throws OcException;
+
+ /**
+ * Method to get the attributes of a resource.
+ *
+ * @param resourceType resourceType of the resource to operate on
+ * @param resourceInterface interface type of the resource to operate on
+ * @param queryParamsMap map which can have the query parameter name and value
+ * @param onGetListener The event handler will be invoked with a map of attribute name and
+ * values. The event handler will also have the result from this Get
+ * operation This will have error codes
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+ public void get(String resourceType,
+ String resourceInterface,
+ Map<String, String> queryParamsMap,
+ OnGetListener onGetListener,
+ QualityOfService qualityOfService) throws OcException {
+ this.get3(
+ resourceType,
+ resourceInterface,
+ queryParamsMap,
+ onGetListener,
+ qualityOfService.getValue());
+ }
+
+ private native void get3(String resourceType,
+ String resourceInterface,
+ Map<String, String> queryParamsMap,
+ OnGetListener onGetListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * Method to set the representation of a resource (via PUT)
+ *
+ * @param representation representation of the resource
+ * @param queryParamsMap Map which can have the query parameter name and value
+ * @param onPutListener event handler The event handler will be invoked with a map of attribute
+ * name and values.
+ * @throws OcException
+ */
+ public native void put(OcRepresentation representation,
+ Map<String, String> queryParamsMap,
+ OnPutListener onPutListener) throws OcException;
+
+ /**
+ * Method to set the representation of a resource (via PUT)
+ *
+ * @param ocRepresentation representation of the resource
+ * @param queryParamsMap Map which can have the query parameter name and value
+ * @param onPutListener event handler The event handler will be invoked with a map of
+ * attribute name and values.
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+ public void put(OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPutListener onPutListener,
+ QualityOfService qualityOfService) throws OcException {
+ this.put1(
+ ocRepresentation,
+ queryParamsMap,
+ onPutListener,
+ qualityOfService.getValue());
+ }
+
+ private native void put1(OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPutListener onPutListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * Method to set the representation 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 ocRepresentation representation of the resource
+ * @param queryParamsMap Map which can have the query parameter name and value
+ * @param onPutListener event handler The event handler will be invoked with a map of
+ * attribute name and values.
+ * @throws OcException
+ */
+ public void put(String resourceType,
+ String resourceInterface,
+ OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPutListener onPutListener) throws OcException {
+ this.put2(
+ resourceType,
+ resourceInterface,
+ ocRepresentation,
+ queryParamsMap,
+ onPutListener);
+ }
+
+ private native void put2(String resourceType,
+ String resourceInterface,
+ OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPutListener onPutListener) throws OcException;
+
+ /**
+ * Method to set the representation 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 ocRepresentation representation of the resource
+ * @param queryParamsMap Map which can have the query parameter name and value
+ * @param onPutListener event handler The event handler will be invoked with a map of
+ * attribute name and values.
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+ public void put(String resourceType,
+ String resourceInterface,
+ OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPutListener onPutListener,
+ QualityOfService qualityOfService) throws OcException {
+ this.put3(
+ resourceType,
+ resourceInterface,
+ ocRepresentation,
+ queryParamsMap,
+ onPutListener,
+ qualityOfService.getValue());
+ }
+
+ private native void put3(String resourceType,
+ String resourceInterface,
+ OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPutListener onPutListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * Method to POST on a resource
+ *
+ * @param ocRepresentation representation of the resource
+ * @param queryParamsMap Map which can have the query parameter name and value
+ * @param onPostListener event handler The event handler will be invoked with a map of
+ * attribute name and values.
+ * @throws OcException
+ */
+ public native void post(OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPostListener onPostListener) throws OcException;
+
+ /**
+ * Method to POST on a resource
+ *
+ * @param ocRepresentation representation of the resource
+ * @param queryParamsMap Map which can have the query parameter name and value
+ * @param onPostListener event handler The event handler will be invoked with a map of
+ * attribute name and values.
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+ public void post(OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPostListener onPostListener,
+ QualityOfService qualityOfService) throws OcException {
+ this.post1(
+ ocRepresentation,
+ queryParamsMap,
+ onPostListener,
+ qualityOfService.getValue());
+ }
+
+ private native void post1(OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPostListener onPostListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * Method 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 ocRepresentation representation of the resource
+ * @param queryParamsMap Map which can have the query parameter name and value
+ * @param onPostListener event handler The event handler will be invoked with a map of
+ * attribute name and values.
+ * @throws OcException
+ */
+ public void post(String resourceType,
+ String resourceInterface,
+ OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPostListener onPostListener) throws OcException {
+ this.post2(
+ resourceType,
+ resourceInterface,
+ ocRepresentation,
+ queryParamsMap,
+ onPostListener);
+ }
+
+ private native void post2(String resourceType,
+ String resourceInterface,
+ OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPostListener onPostListener) throws OcException;
+
+ /**
+ * Method 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 ocRepresentation representation of the resource
+ * @param queryParamsMap Map which can have the query parameter name and value
+ * @param onPostListener event handler The event handler will be invoked with a map of
+ * attribute name and values.
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+ public void post(String resourceType,
+ String resourceInterface,
+ OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPostListener onPostListener,
+ QualityOfService qualityOfService) throws OcException {
+ this.post3(
+ resourceType,
+ resourceInterface,
+ ocRepresentation,
+ queryParamsMap,
+ onPostListener,
+ qualityOfService.getValue());
+ }
+
+ private native void post3(String resourceType,
+ String resourceInterface,
+ OcRepresentation ocRepresentation,
+ Map<String, String> queryParamsMap,
+ OnPostListener onPostListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * Method to perform DELETE operation
+ *
+ * @param onDeleteListener event handler The event handler will have headerOptionList
+ */
+ public native void deleteResource(OnDeleteListener onDeleteListener) throws OcException;
+
+ /**
+ * Method to perform DELETE operation
+ *
+ * @param onDeleteListener event handler The event handler will have headerOptionList
+ * @param qualityOfService the quality of communication
+ */
+ public void deleteResource(OnDeleteListener onDeleteListener,
+ QualityOfService qualityOfService) throws OcException {
+ this.deleteResource1(onDeleteListener,
+ qualityOfService.getValue());
+ }
+
+ private native void deleteResource1(OnDeleteListener onDeleteListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * Method to set observation on the resource
+ *
+ * @param observeType allows the client to specify how it wants to observe
+ * @param queryParamsMap map which can have the query parameter name and value
+ * @param onObserveListener event handler The handler method will be invoked with a map
+ * of attribute name and values.
+ * @throws OcException
+ */
+ public void observe(ObserveType observeType,
+ Map<String, String> queryParamsMap,
+ OnObserveListener onObserveListener) throws OcException {
+ this.observe(
+ observeType.getValue(),
+ queryParamsMap,
+ onObserveListener);
+ }
+
+ private synchronized native void observe(int observeType,
+ Map<String, String> queryParamsMap,
+ OnObserveListener onObserveListener) throws OcException;
+
+ /**
+ * Method to set observation on the resource
+ *
+ * @param observeType allows the client to specify how it wants to observe
+ * @param queryParamsMap map which can have the query parameter name and value
+ * @param onObserveListener event handler The handler method will be invoked with a map
+ * of attribute name and values.
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+ public void observe(ObserveType observeType,
+ Map<String, String> queryParamsMap,
+ OnObserveListener onObserveListener,
+ QualityOfService qualityOfService) throws OcException {
+ this.observe1(
+ observeType.getValue(),
+ queryParamsMap,
+ onObserveListener,
+ qualityOfService.getValue());
+ }
+
+ private synchronized native void observe1(int observeType,
+ Map<String, String> queryParamsMap,
+ OnObserveListener onObserveListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * Method to cancel the observation on the resource
+ *
+ * @throws OcException
+ */
+ public native void cancelObserve() throws OcException;
+
+ /**
+ * Method to cancel the observation on the resource
+ *
+ * @param qualityOfService the quality of communication
+ * @throws OcException
+ */
+ public void cancelObserve(QualityOfService qualityOfService) throws OcException {
+ this.cancelObserve1(qualityOfService.getValue());
+ }
+
+ private native void cancelObserve1(int qualityOfService) throws OcException;
+
+ /**
+ * Method to set header options
+ *
+ * @param headerOptionList List<OcHeaderOption> where header information(header optionID and
+ * optionData is passed
+ */
+ public void setHeaderOptions(List<OcHeaderOption> headerOptionList) {
+ this.setHeaderOptions(headerOptionList.toArray(
+ new OcHeaderOption[headerOptionList.size()])
+ );
+ }
+
+ private native void setHeaderOptions(OcHeaderOption[] headerOptionList);
+
+ /**
+ * Method to unset header options
+ */
+ public native void unsetHeaderOptions();
+
+ /**
+ * Method to get the host address of this resource
+ *
+ * @return host address NOTE: This might or might not be exposed in future due to
+ * security concerns
+ */
+ public native String getHost();
+
+ /**
+ * Method to get the URI for this resource
+ *
+ * @return resource URI
+ */
+ public native String getUri();
+
+ /**
+ * Method to get the connectivity type of this resource
+ *
+ * @return OcConnectivityType connectivity type
+ */
+ public OcConnectivityType getConnectivityType() {
+ return OcConnectivityType.get(
+ this.getConnectivityTypeN()
+ );
+ }
+
+ private native int getConnectivityTypeN();
+
+ /**
+ * Method to get the connectivity flags of this resource
+ *
+ * @return OcConnectivityFlags connectivity type
+ */
+ public OcConnectivityFlags getConnectivityFlags() {
+ OcConnectivityType connType = this.getConnectivityType();
+ int connTypeN = this.getConnectivityTypeN();
+ int flag = connTypeN - connType.getValue();
+ return OcConnectivityFlags.get(flag);
+ }
+
+ /**
+ * Method to provide ability to check if this resource is observable or not
+ *
+ * @return true indicates resource is observable; false indicates resource is not observable
+ */
+ public native boolean isObservable();
+
+ /**
+ * Method to get the list of resource types
+ *
+ * @return List of resource types
+ */
+ public native List<String> getResourceTypes();
+
+ /**
+ * Method to get the list of resource interfaces
+ *
+ * @return List of resource interface
+ */
+ public native List<String> getResourceInterfaces();
+
+ /**
+ * Method 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
+ */
+ public native OcResourceIdentifier getUniqueIdentifier();
+
+ /**
+ * Method to get a string representation of the resource's server ID.
+ * * This is unique per- server independent on how it was discovered.
+ *
+ * @return server ID
+ */
+ public native String getServerId();
+
+ /**
+ * An OnGetListener can be registered via the resource get call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnGetListener {
+ public void onGetCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation);
+
+ public void onGetFailed(Throwable ex);
+ }
+
+ /**
+ * An OnPutListener can be registered via the resource put call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnPutListener {
+ public void onPutCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation);
+
+ public void onPutFailed(Throwable ex);
+ }
+
+ /**
+ * An OnPostListener can be registered via the resource post call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnPostListener {
+ public void onPostCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation);
+
+ public void onPostFailed(Throwable ex);
+ }
+
+ /**
+ * An OnDeleteListener can be registered via the resource delete call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnDeleteListener {
+ public void onDeleteCompleted(List<OcHeaderOption> headerOptionList);
+
+ public void onDeleteFailed(Throwable ex);
+ }
+
+ /**
+ * An OnObserveListener can be registered via the resource observe call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnObserveListener {
+ public void onObserveCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation,
+ int sequenceNumber);
+
+ public void onObserveFailed(Throwable ex);
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ super.finalize();
+
+ dispose();
+ }
+
+ private native void dispose();
+
+ private long mNativeHandle;
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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 all the variables which can be configured/modified as
+// per platform or specific product usage scenarios.
+
+package org.iotivity.base;
+
+public interface OcStackConfig {
+ // max manufacturer name length for OcPlatformInfo supported by server
+ public static final int MAX_MANUFACTURER_NAME_LENGTH = 16;
+ // max manufacturer url length for OcPlatformInfo supported by server
+ public static final int MAX_MANUFACTURER_URL_LENGTH = 32;
+}
\ No newline at end of file
public class CaLeClientInterface {
- private static String SERVICE_UUID = "713d0000-503e-4c75-ba94-3148f18d941e";
+ private static String SERVICE_UUID = "ADE3D529-C784-4F63-A987-EB69F70EE816";
private CaLeClientInterface(Context context) {
List<UUID> uuids = getUuids(scanRecord);
for (UUID uuid : uuids) {
Log.d("CA", "UUID : " + uuid.toString());
- if(uuid.toString().contains(SERVICE_UUID)) {
+ if(uuid.toString().contains(SERVICE_UUID.toLowerCase())) {
Log.d("CA", "we found that has the Device");
caLeScanCallback(device, rssi, scanRecord);
}
--- /dev/null
+build
\ No newline at end of file
--- /dev/null
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion "21.1.1"\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.guiclient"\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.2'\r
+}\r
--- /dev/null
+<?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" 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=":guiclient" />\r
+ </configuration>\r
+ </facet>\r
+ <facet type="android" name="Android">\r
+ <configuration>\r
+ <option name="SELECTED_BUILD_VARIANT" value="debug" />\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
+ <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="support-annotations-21.0.2" level="project" />\r
+ <orderEntry type="library" exported="" name="support-v4-21.0.2" level="project" />\r
+ <orderEntry type="library" exported="" name="iotivity-armeabi-base-release-unspecified" level="project" />\r
+ <orderEntry type="library" exported="" name="appcompat-v7-21.0.2" level="project" />\r
+ </component>\r
+</module>\r
+\r
--- /dev/null
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /opt/android-dev/adt-bundle-linux-x86_64-20140702/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 *;
+#}
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="org.iotivity.guiclient"
+ xmlns:tools="http://schemas.android.com/tools">
+
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ <activity
+ android:name=".MainActivity"
+ android:label="@string/app_name"
+ android:screenOrientation="portrait" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
--- /dev/null
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.content.Context;
+import android.media.Image;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.BaseExpandableListAdapter;
+import android.widget.CompoundButton;
+import android.widget.ImageView;
+import android.widget.ProgressBar;
+import android.widget.SeekBar;
+import android.widget.Switch;
+import android.widget.TextView;
+
+import java.util.List;
+
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE;
+import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.ROOM_TEMPERATURE_RESOURCE_URI;
+
+/**
+ * ExpandableResourceListAdapter knows how to render an ExpandableListView, using a
+ * List of OcResourceInfo objects as the parents of the ExpandableListView,
+ * and OcAttributeInfo objects as the children.
+ *
+ * @see org.iotivity.guiclient.OcAttributeInfo
+ */
+public class ExpandableResourceListAdapter extends BaseExpandableListAdapter {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "ExpandableResourceListAdapter";
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ private List<OcResourceInfo> resourceList;
+ private Context ctx;
+
+ public ExpandableResourceListAdapter(List<OcResourceInfo> resourceList, Context ctx) {
+ this.resourceList = resourceList;
+ this.ctx = ctx;
+ }
+
+ @Override
+ public Object getChild(int groupPosition, int childPosition) {
+ return resourceList.get(groupPosition).getAttributes().get(childPosition);
+ }
+
+ @Override
+ public int getChildrenCount(int groupPosition) {
+ return resourceList.get(groupPosition).getAttributes().size();
+ }
+
+ @Override
+ public long getChildId(int groupPosition, int childPosition) {
+ return resourceList.get(groupPosition).getAttributes().get(childPosition).hashCode();
+ }
+
+ @Override
+ public int getChildType(int groupPosition, int childPosition) {
+ return this.resourceList.get(groupPosition).getAttributes().get(childPosition)
+ .getType().ordinal();
+ }
+
+ @Override
+ public int getChildTypeCount() {
+ return OC_ATTRIBUTE_TYPE.values().length;
+ }
+
+ @Override
+ public View getChildView(final int groupPosition, int childPosition,
+ boolean isLastChild, View convertView, ViewGroup parent) {
+ View v = convertView;
+ if (v == null) {
+ LayoutInflater inflater = (LayoutInflater)ctx.getSystemService
+ (Context.LAYOUT_INFLATER_SERVICE);
+ switch(OC_ATTRIBUTE_TYPE.fromInt(getChildType(groupPosition, childPosition))) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ v = inflater.inflate(R.layout.attribute_layout_progress_bar, parent, false);
+ break;
+ case LIGHT_DIMMER:
+ v = inflater.inflate(R.layout.attribute_layout_slider, parent, false);
+ break;
+ case LIGHT_SWITCH:
+ case PLATFORM_LED_SWITCH:
+ v = inflater.inflate(R.layout.attribute_layout_on_off_switch, parent, false);
+ break;
+ }
+ }
+
+ OcAttributeInfo attribute =
+ resourceList.get(groupPosition).getAttributes().get(childPosition);
+
+ // All attribute icons and names are currently treated the same so we handle them outside
+ // the type-specific inflater functions
+ ImageView attributeIcon = (ImageView) v.findViewById(R.id.attribute_icon_id);
+ attributeIcon.setVisibility(View.VISIBLE);
+ TextView attributeName = (TextView) v.findViewById(R.id.attribute_name_id);
+ attributeName.setText(getAttributeLabelFromType(attribute.getType()));
+ attributeName.setVisibility(View.VISIBLE);
+
+ // Now inflate the rest of the layout in a type-specific way
+ switch(attribute.getType()){
+ case AMBIENT_LIGHT_SENSOR_READING:
+ this.renderAmbientLightSensorReading(v, groupPosition, attribute);
+ break;
+ case LIGHT_DIMMER:
+ this.renderLightDimmer(v, groupPosition, attribute);
+ break;
+ case LIGHT_SWITCH:
+ this.renderLightSwitch(v, groupPosition, attribute);
+ break;
+ case PLATFORM_LED_SWITCH:
+ this.renderPlatformLedSwitch(v, groupPosition, attribute);
+ break;
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ this.renderRoomTemperatureSensorReading(v, groupPosition, attribute);
+ break;
+ }
+
+ return v;
+ }
+
+ @Override
+ public Object getGroup(int groupPosition) {
+ return resourceList.get(groupPosition);
+ }
+
+ @Override
+ public int getGroupCount() {
+ return resourceList.size();
+ }
+
+ @Override
+ public long getGroupId(int groupPosition) {
+ return resourceList.get(groupPosition).hashCode();
+ }
+
+ @Override
+ public View getGroupView(int groupPosition, boolean isExpanded,
+ View convertView, ViewGroup parent) {
+
+ View v = convertView;
+
+ if (v == null) {
+ LayoutInflater inflater = (LayoutInflater)ctx.getSystemService
+ (Context.LAYOUT_INFLATER_SERVICE);
+ v = inflater.inflate(R.layout.resource_list_item_layout, parent, false);
+ }
+
+ TextView resourceName = (TextView) v.findViewById(R.id.resource_name_id);
+ TextView resourceDescription = (TextView) v.findViewById(R.id.resource_description_id);
+ ImageView resourceIcon = (ImageView) v.findViewById(R.id.resource_icon_id);
+
+ OcResourceInfo resource = resourceList.get(groupPosition);
+
+ resourceName.setText(this.getResourceLabelFromType(resource.getType()));
+ resourceDescription.setText(resource.getHost()+resource.getUri());
+ switch (resource.getType()) {
+ case AMBIENT_LIGHT_SENSOR:
+ resourceIcon.setImageResource(R.drawable.iotivity_hex_icon);
+ break;
+ case LIGHT:
+ resourceIcon.setImageResource(R.drawable.light_icon);
+ break;
+ case PLATFORM_LED:
+ resourceIcon.setImageResource(R.drawable.led_icon);
+ break;
+ case ROOM_TEMPERATURE_SENSOR:
+ resourceIcon.setImageResource(R.drawable.thermometer_icon);
+ break;
+ default:
+ resourceIcon.setImageResource(R.drawable.iotivity_hex_icon);
+ break;
+ }
+
+ return v;
+ }
+
+ @Override
+ public boolean hasStableIds() {
+ return true;
+ }
+
+ @Override
+ public boolean isChildSelectable(int groupPosition, int childPosition) {
+ return true;
+ }
+
+ /**
+ * Type-specific layout render for Ambient Light Sensor reading attribute.
+ */
+ private void renderAmbientLightSensorReading(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // Render attributeValue
+ TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
+ attributeValue.setText(String.valueOf(attribute.getValueInt()));
+ attributeValue.setVisibility(View.VISIBLE);
+
+ // Render progressBar
+ ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.attribute_progress_bar);
+ progressBar.setMax(100); // display as percent from 0-100
+ progressBar.setProgress(attribute.getValueAsPercentOfMax());
+ progressBar.setVisibility(View.VISIBLE);
+ }
+
+ /**
+ * Type-specific layout render for Light Dimmer attribute.
+ */
+ private void renderLightDimmer(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // Render attributeValue
+ TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
+ attributeValue.setText(String.valueOf(attribute.getValueInt()));
+ attributeValue.setVisibility(View.VISIBLE);
+
+ // Render SeekBar
+ SeekBar slider = (SeekBar) view.findViewById(R.id.attribute_slider);
+ slider.setMax(attribute.getValueMax());
+ slider.setProgress(attribute.getValueInt());
+ slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
+ private int mSliderVal;
+ @Override
+ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("onProgressChanged(%s)", progress));
+ this.mSliderVal = progress;
+ }
+ @Override
+ public void onStartTrackingTouch(SeekBar seekBar) {}
+ @Override
+ public void onStopTrackingTouch(SeekBar seekBar) {
+ if (LOCAL_LOGV) Log.v(TAG, "onStopTrackingTouch()");
+ if(ctx instanceof MainActivity) {
+ // call MainActivity
+ ((MainActivity) ctx).setLightDimmerLevel(resourceList.get(groupPosition),
+ this.mSliderVal);
+ }
+ }
+ });
+ slider.setVisibility(View.VISIBLE);
+ }
+
+ /**
+ * Type-specific layout render for Light Switch attribute.
+ */
+ private void renderLightSwitch(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // Render attributeValue
+ TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
+ if(false == attribute.getValueBool()) {
+ attributeValue.setText("off");
+ } else {
+ attributeValue.setText("on");
+ }
+ attributeValue.setVisibility(View.VISIBLE);
+
+ // Render Switch
+ Switch toggleSwitch = (Switch) view.findViewById(R.id.attribute_switch);
+ toggleSwitch.setText(this.ctx.getString(R.string.oc_light_switch_toggle_text));
+ toggleSwitch.setChecked(attribute.getValueBool());
+ toggleSwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("onCheckedChanged(%s)", isChecked));
+ if(ctx instanceof MainActivity) {
+ // call MainActivity
+ ((MainActivity) ctx).toggleLightSwitch(resourceList.get(groupPosition),
+ isChecked);
+ }
+ }
+ });
+ toggleSwitch.setVisibility(View.VISIBLE);
+ }
+
+ /**
+ * Type-specific layout render for LED Switch attribute.
+ */
+ private void renderPlatformLedSwitch(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // Render attributeValue
+ TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
+ if(1 == attribute.getValueInt()) {
+ attributeValue.setText("on");
+ } else {
+ attributeValue.setText("off");
+ }
+ attributeValue.setVisibility(View.VISIBLE);
+
+ // Render Switch
+ Switch toggleSwitch = (Switch) view.findViewById(R.id.attribute_switch);
+ toggleSwitch.setText(this.ctx.getString(R.string.oc_led_switch_toggle_text));
+ toggleSwitch.setChecked(1 == attribute.getValueInt());
+ toggleSwitch.setOnCheckedChangeListener( new Switch.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("onCheckedChanged(%s)", isChecked));
+ if(ctx instanceof MainActivity) {
+ // call MainActivity
+ ((MainActivity) ctx).toggleLedSwitch(resourceList.get(groupPosition),
+ isChecked);
+ }
+ }
+ });
+ toggleSwitch.setVisibility(View.VISIBLE);
+ }
+
+ /**
+ * Type-specific layout render for Room Temperature Sensor Reading attribute.
+ */
+ private void renderRoomTemperatureSensorReading(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // this happens to have the same behavior as ambient light sensor, so just re-use
+ this.renderAmbientLightSensorReading(view, groupPosition, attribute);
+ }
+
+ private String getAttributeLabelFromType(OC_ATTRIBUTE_TYPE type) {
+ switch (type) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ return ctx.getString(R.string.ui_attribute_label_ambient_light_sensor_reading);
+ case LIGHT_DIMMER:
+ return ctx.getString(R.string.ui_attribute_label_light_dimmer);
+ case LIGHT_SWITCH:
+ return ctx.getString(R.string.ui_attribute_label_light_switch);
+ case PLATFORM_LED_SWITCH:
+ return ctx.getString(R.string.ui_attribute_label_led_switch);
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ return ctx.getString(R.string.ui_attribute_label_room_temperature_sensor_reading);
+ default:
+ Log.w(TAG, "getAttributeLabelFromType(): unrecognized attribute type.");
+ return "Attribute:";
+ }
+ }
+
+ private String getResourceLabelFromType(OcResourceInfo.OC_RESOURCE_TYPE type) {
+ if (LOCAL_LOGV) Log.v(TAG, "getResourceLabelFromType()");
+
+ switch(type) {
+ case AMBIENT_LIGHT_SENSOR:
+ return ctx.getString(R.string.ui_resource_label_ambient_light_sensor);
+ case LIGHT:
+ return ctx.getString(R.string.ui_resource_label_light);
+ case PLATFORM_LED:
+ return ctx.getString(R.string.ui_resource_label_platform_led);
+ case ROOM_TEMPERATURE_SENSOR:
+ return ctx.getString(R.string.ui_resource_label_room_temperature_sensor);
+ default:
+ Log.w(TAG, "getResourceLabelFromType(): unrecognized resource type.");
+ return "Resource:";
+ }
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.support.v7.app.ActionBarActivity;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.ExpandableListView;
+import android.widget.ProgressBar;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER;
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH;
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH;
+import static org.iotivity.guiclient.R.id.expandableResourceListView;
+
+/**
+ * MainActivity instantiates a ExpandableListView of type ExpandableResourceListView, and
+ * also creates and starts a OcWorker object to handle the IoTivity specific work.
+ *
+ * @see org.iotivity.guiclient.OcWorker
+ * @see org.iotivity.guiclient.OcWorkerListener
+ * @see org.iotivity.guiclient.ExpandableResourceListAdapter
+ */
+public class MainActivity
+ extends ActionBarActivity
+ implements OcWorkerListener, View.OnClickListener, ExpandableListView.OnChildClickListener {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "MainActivity";
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ /**
+ * The data structure behind the displayed List of resources and attributes.
+ */
+ private List<OcResourceInfo> mResourceList;
+
+ /**
+ * The custom adapter for displaying the ResourceListItem List
+ */
+ private ExpandableResourceListAdapter mResourceListAdapter;
+
+ /**
+ * The OIC-aware worker class which does all the OIC API interaction
+ * and handles the results, notifying MainActivity whenever an event
+ * requires a UI update.
+ */
+ private OcWorker mOcWorker;
+
+ /**
+ * Preserve a ref to Action Bar Menu for changing progress icon
+ */
+ private Menu optionsMenu;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ if (LOCAL_LOGV) Log.v(TAG, "onCreate()");
+
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.activity_main);
+
+ // start the OcWorker thread and register as a listener
+ if(null == this.mOcWorker) {
+ this.mOcWorker = new OcWorker(this);
+ this.mOcWorker.start(); // configures the OIC platform and wait for further calls
+ this.mOcWorker.registerListener(this);
+ }
+
+ // init the Resource display list
+ if(null == this.mResourceList) {
+ this.mResourceList = new ArrayList<>();
+ }
+
+ // init the ListView Adapter
+ if(null == this.mResourceListAdapter) {
+ this.mResourceListAdapter = new ExpandableResourceListAdapter(this.mResourceList,
+ this);
+ }
+
+ // init the Expandable List View
+ ExpandableListView exListView =
+ (ExpandableListView) findViewById(expandableResourceListView);
+ exListView.setIndicatorBounds(5, 5);
+ exListView.setIndicatorBounds(0, 20);
+ exListView.setAdapter(this.mResourceListAdapter);
+ exListView.setOnChildClickListener(this);
+ }
+
+ @Override
+ public void onRestoreInstanceState(Bundle savedInstanceState) {
+ if (LOCAL_LOGV) Log.v(TAG, "onRestoreInstanceState()");
+ }
+
+ @Override
+ public void onSaveInstanceState(Bundle outState) {
+ if (LOCAL_LOGV) Log.v(TAG, "onSaveInstanceState()");
+ }
+
+ @Override
+ public void onClick(View v) {
+ if (LOCAL_LOGV) Log.v(TAG, "onClick()");
+
+ this.setRefreshActionButtonState(false);
+ }
+
+ @Override
+ public boolean onChildClick(ExpandableListView parent,
+ View v,
+ int groupPosition,
+ int childPosition,
+ long id) {
+ if (LOCAL_LOGV) Log.v(TAG, "onChildClick()");
+
+ this.mOcWorker.doGetResource(mResourceList.get(groupPosition));
+
+ return false;
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ if (LOCAL_LOGV) Log.v(TAG, "onCreateOptionsMenu()");
+
+ // save a reference for use in controlling refresh icon later
+ this.optionsMenu = menu;
+
+ // Inflate the menu; this adds items to the action bar if it is present.
+ getMenuInflater().inflate(R.menu.menu_main, menu);
+
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("onOptionsItemSelected(%s)", item.toString()));
+ // 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();
+
+ // Handle the "settings" icon/text click
+ if (id == R.id.action_settings) {
+ return true;
+ }
+
+ // Handle the "developer test" icon/text click
+ if (id == R.id.action_test) {
+ return true;
+ }
+
+ // Handle the trash can "discard" icon click
+ if (id == R.id.action_discard) {
+ AlertDialog diaBox = confirmDiscard();
+ diaBox.show();
+ }
+
+ // Handle the refresh/progress icon click
+ if (id == R.id.action_refresh) {
+ // show the indeterminate progress bar
+ this.setRefreshActionButtonState(true);
+ // use OcWorker to discover resources
+ this.mOcWorker.doDiscoverResources();
+ }
+
+ return super.onOptionsItemSelected(item);
+ }
+
+ /**
+ * Handle a resource changed callback from OcWorker by posting a runnable to our
+ * own UI-safe looper/handler
+ */
+ @Override
+ public void onResourceChanged(final OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "onResourceChanged()");
+
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ // in case we were waiting for a refresh, hide the indeterminate progress bar
+ setRefreshActionButtonState(false);
+
+ mResourceListAdapter.notifyDataSetChanged();
+ }
+ });
+ }
+
+ /**
+ * Handle a new resource found callback from OcWorker by posting a runnable to our
+ * own UI-safe looper/handler
+ */
+ @Override
+ public void onResourceFound(final OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "onResourceFound()");
+
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ // in case we were waiting for a refresh, hide the indeterminate progress bar
+ setRefreshActionButtonState(false);
+
+ // if resource not already in list, add it
+ if(!mResourceList.contains(resourceInfo)) {
+ mResourceList.add(resourceInfo);
+ }
+
+ mResourceListAdapter.notifyDataSetChanged();
+ }
+ });
+ }
+
+ public void toggleLedSwitch(OcResourceInfo resourceInfo, boolean onOff) {
+ if (LOCAL_LOGV) Log.d(TAG, String.format("toggleLedSwitch(%s, %s)",
+ resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(onOff)));
+
+ // send a msg to OcWorker to put the switch value
+ for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
+ if(ai.getType() == PLATFORM_LED_SWITCH) {
+ if(onOff) {
+ ai.setValueInt(1);
+ } else {
+ ai.setValueInt(0);
+ }
+ }
+ }
+ this.mOcWorker.doPutResource(resourceInfo);
+ }
+
+ public void toggleLightSwitch(OcResourceInfo resourceInfo, boolean onOff) {
+ if (LOCAL_LOGV) Log.d(TAG, String.format("toggleLightSwitch(%s, %s)",
+ resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(onOff)));
+
+ // send a msg to OcWorker to put the switch value
+ for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
+ if(ai.getType() == LIGHT_SWITCH) {
+ ai.setValueBool(onOff);
+ }
+ }
+ this.mOcWorker.doPutResource(resourceInfo);
+ }
+
+ public void setLightDimmerLevel(OcResourceInfo resourceInfo, int value) {
+ if (LOCAL_LOGV) Log.d(TAG, String.format("setLightDimmerLevel(%s, %s)",
+ resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(value)));
+
+ // send a msg to OcWorker to put the switch value
+ for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
+ if(ai.getType() == LIGHT_DIMMER) {
+ ai.setValueInt(value);
+ }
+ }
+ this.mOcWorker.doPutResource(resourceInfo);
+ }
+
+ /**
+ * Sets the Action Bar icon to "progress" (spinning circle), or returns it to refresh icon
+ *
+ * @param refreshing true sets icon to animated "progress" spinner; false to static
+ * refresh icon
+ */
+ private void setRefreshActionButtonState(final boolean refreshing) {
+ if (this.optionsMenu != null) {
+ final MenuItem refreshItem
+ = this.optionsMenu
+ .findItem(R.id.action_refresh);
+ if (refreshItem != null) {
+ if (refreshing) {
+ refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
+ ProgressBar progressBar =
+ (ProgressBar) findViewById(R.id.find_resource_progress_bar);
+ progressBar.setOnClickListener(this);
+
+ } else {
+ refreshItem.setActionView(null);
+ }
+ }
+ }
+ }
+
+ private AlertDialog confirmDiscard()
+ {
+ if (LOCAL_LOGV) Log.v(TAG, "confirmDiscard()");
+
+ return new AlertDialog.Builder(this)
+ .setTitle("Clear Resource List?")
+ .setIcon(R.drawable.ic_action_discard_dark)
+ .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ // clear OcWorker's list
+ mOcWorker.doClearResources();
+ // in case its running, hide the indeterminate progress bar
+ setRefreshActionButtonState(false);
+ // clear our local data model list
+ mResourceList.clear();
+ mResourceListAdapter.notifyDataSetChanged();
+ dialog.dismiss();
+ }
+ })
+
+ .setNegativeButton("No", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ }
+ })
+
+ .create();
+ }
+
+}
--- /dev/null
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.util.Log;
+
+import java.io.Serializable;
+
+/**
+ * Created by nathanhs on 12/28/15.
+ */
+public class OcAttributeInfo implements Serializable {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "OcAttributeInfo";
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ private static final int AMBIENT_LIGHT_SENSOR_READING_MAX = 4096;
+ private static final int LIGHT_DIMMER_MAX = 100;
+ private static final int LIGHT_SWITCH_MAX = 1;
+ private static final int PLATFORM_LED_SWITCH_MAX = 1;
+ // TODO: once the temp getValueInt works, figure out how to scale this properly
+ private static final int ROOM_TEMPERATURE_SENSOR_READING_MAX = 4096;
+
+ /**
+ * These are the resource types supported by OcResourceInfo.
+ */
+ public enum OC_ATTRIBUTE_TYPE {
+ AMBIENT_LIGHT_SENSOR_READING,
+ LIGHT_DIMMER,
+ LIGHT_SWITCH,
+ PLATFORM_LED_SWITCH,
+ ROOM_TEMPERATURE_SENSOR_READING;
+
+ private static final OC_ATTRIBUTE_TYPE[] values = OC_ATTRIBUTE_TYPE.values();
+
+ public static OC_ATTRIBUTE_TYPE fromInt(int i) {
+ return values[i];
+ }
+ }
+
+ private boolean mCurrentlyObserved;
+ private final int mId;
+ private static int mIdInitializer = 0;
+ private final boolean mObservable = true; //TODO BROKEN fix when implementing observe
+ private final OcResourceInfo mParentResource;
+ private final boolean mReadOnly;
+ private final OC_ATTRIBUTE_TYPE mType;
+ private boolean mValueBool; // used if attribute has a boolean value
+ private int mValueInt; // used if attribute has an int value
+ private String mValueString; // used if attribute has a String value
+ private final int mValueMax;
+
+ public OcAttributeInfo(OC_ATTRIBUTE_TYPE type, OcResourceInfo parent) {
+ if (LOCAL_LOGV) Log.v(TAG, "OcAttributeInfo() constructor");
+
+ this.mId = OcAttributeInfo.mIdInitializer++; // give a unique Id from other OcResourceInfos
+ this.mParentResource = parent;
+ this.mReadOnly = this.getReadOnlyBasedOnType(type);
+ this.mType = type;
+ this.mValueBool = false;
+ this.mValueInt = 0;
+ this.mValueString = "error";
+ this.mValueMax = this.getMaxAttributeValueBasedOnType(type);
+ }
+
+ public int getId() {
+ return mId;
+ }
+
+ public OC_ATTRIBUTE_TYPE getType() {
+ return mType;
+ }
+
+ public boolean getValueBool() {
+ return this.mValueBool;
+ }
+
+ public int getValueInt() {
+ return this.mValueInt;
+ }
+
+ public int getValueMax() {
+ return mValueMax;
+ }
+
+ public String getValueString() {
+ return this.mValueString;
+ }
+
+ public int getValueAsPercentOfMax() {
+ return (this.mValueInt*100)/this.mValueMax;
+ }
+
+ public boolean isCurrentlyObserved() {
+ return this.mCurrentlyObserved;
+ }
+
+ public boolean isObservable() {
+ return this.mObservable;
+ }
+
+ public boolean isReadOnly() {
+ return mReadOnly;
+ }
+
+ public void setCurrentlyObserved(boolean currentlyObserved) {
+ this.mCurrentlyObserved = currentlyObserved;
+ }
+
+ public void setValueBool(boolean value) {
+ this.mValueBool = value;
+ }
+
+ public void setValueInt(int value) {
+ this.mValueInt = value;
+ }
+
+ public void setValueString(String value) {
+ this.mValueString = value;
+ }
+
+ private int getMaxAttributeValueBasedOnType(OC_ATTRIBUTE_TYPE type) {
+ switch(type) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ return AMBIENT_LIGHT_SENSOR_READING_MAX;
+ case LIGHT_DIMMER:
+ return LIGHT_DIMMER_MAX;
+ case LIGHT_SWITCH:
+ return LIGHT_SWITCH_MAX;
+ case PLATFORM_LED_SWITCH:
+ return PLATFORM_LED_SWITCH_MAX;
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ return ROOM_TEMPERATURE_SENSOR_READING_MAX;
+ default:
+ Log.w(TAG, "getMaxAttributeValueBasedOnType(): unrecognized attribute type.");
+ return 0;
+ }
+ }
+
+ private boolean getReadOnlyBasedOnType(OC_ATTRIBUTE_TYPE type) {
+ switch(type) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ return true;
+ case LIGHT_DIMMER:
+ case LIGHT_SWITCH:
+ case PLATFORM_LED_SWITCH:
+ return false;
+ default:
+ Log.w(TAG, "getReadOnlyBasedOnType(): unrecognized attribute type.");
+ return false;
+ }
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+/**
+ * OcProtocolStrings contains the IoTivity-specific constant values. To add another supported
+ * Resource or Interface type to this app, begin by adding the new strings here, and then
+ * find the places throughout the app where Resource-specific case switches occur, and add
+ * the newly-supported type there.
+ */
+public interface OcProtocolStrings {
+ // OIC core protocol strings
+ public static final String COAP_CORE = "coap://224.0.1.187/oic/res";
+ public static final String RESOURCE_TYPE_QUERY = "?rt=";
+ public static final String INTERFACE_QUERY = "?if=";
+ // find resource queries
+ public static final String CORE_LIGHT = "core.light";
+ public static final String CORE_EDISON_RESOURCES = "core.edison.resources";
+ // resource URIs
+ public static final String LIGHT_RESOURCE_URI = "/a/light";
+ public static final String LIGHT_RESOURCE_URI2 = "/light0";
+ public static final String LIGHT_RESOURCE_URI3 = "/a/light1";
+ public static final String ROOM_TEMPERATURE_RESOURCE_URI = "/temperature";
+ public static final String AMBIENT_LIGHT_RESOURCE_URI = "/ambientlight";
+ public static final String PLATFORM_LED_RESOURCE_URI = "/led";
+ // attribute keys for set() calls
+ public static final String LIGHT_SWITCH_RESOURCE_KEY = "state";
+ public static final String LIGHT_DIMMER_RESOURCE_KEY = "power";
+ public static final String ROOM_TEMPERATURE_RESOURCE_KEY = "temperature";
+ public static final String AMBIENT_LIGHT_RESOURCE_KEY = "ambientlight";
+ public static final String PLATFORM_LED_RESOURCE_KEY = "switch";
+}
--- /dev/null
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.util.Log;
+
+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 java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.AMBIENT_LIGHT_SENSOR_READING;
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER;
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH;
+import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_KEY;
+import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_DIMMER_RESOURCE_KEY;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI2;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI3;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_SWITCH_RESOURCE_KEY;
+import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_KEY;
+import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.ROOM_TEMPERATURE_RESOURCE_URI;
+
+/**
+ * OcResourceInfo is a wrapper object for the OcResource object. It implements the Resource-
+ * specific callbacks, and abstracts the IoTivity implementation details from the application.
+ *
+ * In order to use OcResourceInfo, an application should implement the OcResourceInfoListener
+ * interface, which is called when the OcResourceInfo changes in any meaningful way.
+ */
+public class OcResourceInfo
+ implements OcResource.OnGetListener, OcResource.OnPutListener, Serializable {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "OcResourceInfo";
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ /**
+ * These are the resource types supported by OcResourceInfo. They should have corresponding
+ * URI strings in the OcProtocolStrings interface.
+ */
+ public enum OC_RESOURCE_TYPE {
+ AMBIENT_LIGHT_SENSOR,
+ LIGHT,
+ PLATFORM_LED,
+ ROOM_TEMPERATURE_SENSOR;
+
+ private static final OC_RESOURCE_TYPE[] values = OC_RESOURCE_TYPE.values();
+
+ public static OC_RESOURCE_TYPE fromInt(int i) {
+ return values[i];
+ }
+ }
+
+ private List<OcAttributeInfo> mAttributes;
+ private final String mHost;
+ private final int mId;
+ private static int mIdInitializer = 0;
+ private List<OcResourceInfoListener> mListeners;
+ private final OcResource mResource;
+ private final OC_RESOURCE_TYPE mType;
+ private final String mUri;
+
+ public interface OcResourceInfoListener {
+ public void onResourceInfoChanged(OcResourceInfo resourceInfo);
+ }
+
+
+ public OcResourceInfo(OcResource resource, OcResourceInfoListener changeListener) {
+ if (LOCAL_LOGV) Log.v(TAG, "OcResourceInfo() constructor");
+
+ this.mAttributes = new ArrayList<>();
+ this.mHost = resource.getHost();
+ this.mId = OcResourceInfo.mIdInitializer++; // give a unique Id from other OcResourceInfos
+ this.mListeners = new ArrayList<>();
+ this.mListeners.add(changeListener);
+ this.mResource = resource;
+ this.mType = this.getResourceTypeFromUri(resource.getUri());
+ this.mUri = resource.getUri();
+
+ }
+
+ public void registerListener(OcResourceInfoListener changeListener) {
+ if(null == this.mListeners) {
+ Log.e(TAG, "registerListener(): null mListeners List");
+ } else {
+ boolean alreadyRegistered = false;
+ for(OcResourceInfoListener rl : this.mListeners) {
+ if(changeListener == rl) {
+ alreadyRegistered = true;
+ }
+ }
+ if(!alreadyRegistered) {
+ this.mListeners.add(changeListener);
+ }
+ }
+ }
+
+ public OC_RESOURCE_TYPE getType() {
+ return this.mType;
+ }
+
+ public String getHost() {
+ return this.mHost;
+ }
+
+ public String getUri() {
+ return this.mUri;
+ }
+
+ @Override
+ public void onGetFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ }
+ Log.e(TAG, throwable.toString());
+ }
+
+ @Override
+ public void onPutFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ }
+ Log.e(TAG, throwable.toString());
+ }
+
+ public List<OcAttributeInfo> getAttributes() {
+ return this.mAttributes;
+ }
+
+ public void doOcGet() {
+ if(null != this.mResource) {
+ try {
+ this.mResource.get(new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.getMessage());
+ }
+ } else {
+ Log.e(TAG, "doOcGet(): null mResource");
+ }
+ }
+
+ public void doOcPut(OcAttributeInfo attribute) {
+ if (LOCAL_LOGV) Log.v(TAG, "doOcPut()");
+
+ if(attribute.isReadOnly()) {
+ Log.w(TAG, String.format("doOcPut(): %s attribute is read only; skipping put!",
+ attribute.getType()));
+ } else {
+ if (null != this.mResource) {
+ try {
+ OcRepresentation representation = new OcRepresentation();
+ switch (attribute.getType()) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ break;
+ case LIGHT_DIMMER:
+ representation.setValueInt(LIGHT_DIMMER_RESOURCE_KEY,
+ attribute.getValueInt());
+ // This 'sw' logic is here because the current IoTivity Light forces
+ // the switch to "false" if the switch val is not specified.
+ boolean sw = true;
+ for(OcAttributeInfo ai : this.mAttributes) {
+ if(ai.getType() == LIGHT_SWITCH) {
+ sw = ai.getValueBool();
+ }
+ }
+ representation.setValueBool(LIGHT_SWITCH_RESOURCE_KEY, sw);
+ break;
+ case LIGHT_SWITCH:
+ representation.setValueBool(LIGHT_SWITCH_RESOURCE_KEY,
+ attribute.getValueBool());
+ break;
+ case PLATFORM_LED_SWITCH:
+ representation.setValueInt(PLATFORM_LED_RESOURCE_KEY,
+ attribute.getValueInt());
+ break;
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ break;
+ default:
+ break;
+ }
+ this.mResource.put(representation, new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.getMessage());
+ }
+ } else {
+ Log.e(TAG, "doOcGet(): null mResource");
+ }
+ }
+ }
+
+ private static Object onGetCompletedLock = new Object();
+ @Override
+// public void onGetCompleted(HeaderOptions headerOptions, OcRepresentation ocRepresentation) {
+ public void onGetCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ synchronized (onGetCompletedLock) {
+ if (LOCAL_LOGV) Log.v(TAG, "enter -> onGetCompleted()");
+ if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis = %s", this.toString()));
+ if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis.mType = %s", this.mType));
+
+ this.mAttributes.clear();
+ switch(this.mType) {
+ case AMBIENT_LIGHT_SENSOR:
+ int ambientLightVal = ocRepresentation.getValueInt(AMBIENT_LIGHT_RESOURCE_KEY);
+ if (LOCAL_LOGV) Log.v(TAG,
+ String.format("%s int value of %s attribute = %d",
+ mType, AMBIENT_LIGHT_RESOURCE_KEY, ambientLightVal));
+ OcAttributeInfo ambientAttribute = new OcAttributeInfo(
+ AMBIENT_LIGHT_SENSOR_READING, this);
+ ambientAttribute.setValueInt(ambientLightVal);
+ this.mAttributes.add(ambientAttribute);
+ break;
+ case LIGHT:
+ // do switch first
+ boolean lightSwitchVal = ocRepresentation.getValueBool(LIGHT_SWITCH_RESOURCE_KEY);
+ OcAttributeInfo lightSwitchAttribute = new OcAttributeInfo(
+ LIGHT_SWITCH, this);
+ lightSwitchAttribute.setValueBool(lightSwitchVal);
+ this.mAttributes.add(lightSwitchAttribute);
+ // then dimmer
+ int dimmerVal = ocRepresentation.getValueInt(LIGHT_DIMMER_RESOURCE_KEY);
+ OcAttributeInfo dimmerAttribute = new OcAttributeInfo(
+ LIGHT_DIMMER, this);
+ dimmerAttribute.setValueInt(dimmerVal);
+ this.mAttributes.add(dimmerAttribute);
+ break;
+ case PLATFORM_LED:
+ int ledVal = ocRepresentation.getValueInt(PLATFORM_LED_RESOURCE_KEY);
+ if (LOCAL_LOGV) Log.v(TAG,
+ String.format("%s int value of %s attribute = %d",
+ mType, PLATFORM_LED_RESOURCE_KEY, ledVal));
+ OcAttributeInfo ledAttribute = new OcAttributeInfo(
+ OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH, this);
+ ledAttribute.setValueInt(ledVal);
+ this.mAttributes.add(ledAttribute);
+ break;
+ case ROOM_TEMPERATURE_SENSOR:
+ int temperatureVal = 98;
+ Log.w(TAG, "getting 'temperature' value is causing crash;" +
+ " skipping and using 98.");
+ // TODO This call crashes in the native JNI code. The example .cpp
+ // app receives a double for the Room Temp key, but the Java API
+ // doesn't support getValueDouble yet.
+ // Debug crash when API fixed?
+// temperatureVal = ocRepresentation.getValueInt(ROOM_TEMPERATURE_RESOURCE_KEY);
+ if (LOCAL_LOGV) Log.v(TAG,
+ String.format("%s int value of 'temperature' attribute = %d",
+ mType, temperatureVal));
+ OcAttributeInfo temperatureAttribute = new OcAttributeInfo(
+ OcAttributeInfo.OC_ATTRIBUTE_TYPE.ROOM_TEMPERATURE_SENSOR_READING,
+ this);
+ temperatureAttribute.setValueInt(temperatureVal);
+ this.mAttributes.add(temperatureAttribute);
+ break;
+ }
+ this.notifyListeners();
+ if (LOCAL_LOGV) Log.v(TAG, "exit <- onGetCompleted()");
+ }
+ }
+
+ /**
+ * Should be called whenever any Resource or Attribute values change on this object.
+ */
+ private void notifyListeners() {
+ if (LOCAL_LOGV) Log.v(TAG, "notifyListeners()");
+
+ for(OcResourceInfoListener l : this.mListeners) {
+ l.onResourceInfoChanged(this);
+ }
+ }
+
+ private Object onPutCompletedLock = new Object();
+ @Override
+ public void onPutCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ synchronized (onPutCompletedLock) {
+ if (LOCAL_LOGV) Log.v(TAG, "enter -> onPutCompleted()");
+ if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis = %s", this.toString()));
+ if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis.mType = %s", this.mType));
+
+ switch(this.mType) {
+ case AMBIENT_LIGHT_SENSOR:
+ Log.w(TAG, String.format("onPutCompleted(): %s is a readonly attribute type.",
+ this.mType));
+ break;
+ case LIGHT:
+ // do switch first
+ boolean lightSwitchVal = ocRepresentation.getValueBool(LIGHT_SWITCH_RESOURCE_KEY);
+ for(OcAttributeInfo ai : this.mAttributes) {
+ if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH) {
+ ai.setValueBool(lightSwitchVal);
+ }
+ }
+ // then dimmer
+ int dimmerVal = ocRepresentation.getValueInt(LIGHT_DIMMER_RESOURCE_KEY);
+ for(OcAttributeInfo ai : this.mAttributes) {
+ if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER) {
+ ai.setValueInt(dimmerVal);
+ }
+ }
+ break;
+ case PLATFORM_LED:
+ int value = ocRepresentation.getValueInt(PLATFORM_LED_RESOURCE_KEY);
+ for(OcAttributeInfo ai : this.mAttributes) {
+ if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH) {
+ ai.setValueInt(value);
+ }
+ }
+ break;
+ case ROOM_TEMPERATURE_SENSOR:
+ Log.w(TAG, String.format("onPutCompleted(): %s is a readonly attribute type.",
+ this.mType));
+ break;
+ }
+ this.notifyListeners();
+ if (LOCAL_LOGV) Log.v(TAG, "exit <- onPutCompleted()");
+ }
+ }
+
+ private OC_RESOURCE_TYPE getResourceTypeFromUri(String uri) {
+ if (LOCAL_LOGV) Log.v(TAG, "getResourceTypeFromUri()");
+
+ switch(uri) {
+ case LIGHT_RESOURCE_URI:
+ case LIGHT_RESOURCE_URI2:
+ case LIGHT_RESOURCE_URI3:
+ return OC_RESOURCE_TYPE.LIGHT;
+ case AMBIENT_LIGHT_RESOURCE_URI:
+ return OC_RESOURCE_TYPE.AMBIENT_LIGHT_SENSOR;
+ case PLATFORM_LED_RESOURCE_URI:
+ return OC_RESOURCE_TYPE.PLATFORM_LED;
+ case ROOM_TEMPERATURE_RESOURCE_URI:
+ return OC_RESOURCE_TYPE.ROOM_TEMPERATURE_SENSOR;
+ default:
+ Log.w(TAG, "getResourceTypeFromUri(): unsupported resource '" + uri + "'" );
+ }
+ return null;
+ }
+}
--- /dev/null
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.util.Log;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.iotivity.guiclient.OcProtocolStrings.COAP_CORE;
+import static org.iotivity.guiclient.OcProtocolStrings.CORE_EDISON_RESOURCES;
+import static org.iotivity.guiclient.OcProtocolStrings.CORE_LIGHT;
+import static org.iotivity.guiclient.OcProtocolStrings.INTERFACE_QUERY;
+import static org.iotivity.guiclient.OcProtocolStrings.RESOURCE_TYPE_QUERY;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_CLEAR_RESOURCES;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_DISCOVER_RESOURCES;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_GET_RESOURCE;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_PUT_RESOURCE;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.fromInt;
+
+/**
+ * OcWorker
+ *
+ * A class designed to encapsulate the OIC API functionality. OcWorker has its own
+ * thread which is used to call all OIC APIs. To get results back from OcWorker,
+ * implement the interface OcWorkerListener, and call registerListener().
+ *
+ * @see org.iotivity.guiclient.OcWorkerListener
+ *
+ * Created by nathanhs on 12/22/15.
+ */
+public class OcWorker extends Thread
+ implements OcPlatform.OnResourceFoundListener, OcResourceInfo.OcResourceInfoListener {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "OcWorker";
+ private Context mContext;
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ /**
+ * NOTE: DO NOT assign non-default values to these enums!
+ * The correctness of "fromInt()" depends on the enum values not being
+ * overridden. For example DO_TEST = 100, RESULT_TEST = 101.. would BREAK the
+ * fromInt() function. There are designs which can account for arbitrary enum
+ * values, but they are less desirable for other reasons and since we do not
+ * need to use any specific value, this design is the best for this case.
+ */
+
+ /**
+ * These "IN" message types are for posting API-generated request actions
+ * to our OcWorker queue.
+ */
+ public enum OCW_IN_MSG {
+ DO_TEST, // developer testing only
+ DO_DISCOVER_RESOURCES,
+ DO_CLEAR_RESOURCES,
+ DO_GET_RESOURCE,
+ DO_PUT_RESOURCE,
+ DO_OBSERVE_RESOURCE,
+ DO_STOP_OBSERVING_RESOURCE;
+
+ private static final OCW_IN_MSG[] values = values();
+
+ public static OCW_IN_MSG fromInt(int i) {
+ return values[i];
+ }
+ }
+
+ /**
+ * These events are for internally putting work on our thread's looper
+ * queue, usually in a callback where we don't want to do work on the
+ * callback thread.
+ */
+ private enum OC_EVENT {
+ OIC_RESOURCE_FOUND,
+ OIC_RESOURCE_CHANGED;
+
+ private static final OC_EVENT[] values = OC_EVENT.values();
+
+ public static OC_EVENT fromInt(int i) {
+ return values[i];
+ }
+ }
+
+ private Handler mDoMsgHandler;
+
+ private Handler mOcEventHandler;
+
+ /**
+ * The OcResourceInfo List
+ */
+ private ArrayList<OcResourceInfo> mOcResourceInfoList;
+
+ /**
+ * The types of OIC Resources included in "FindResource" calls by this object.
+ */
+ private final String[] mOcFindQueries = {
+ COAP_CORE + RESOURCE_TYPE_QUERY + CORE_LIGHT,
+ COAP_CORE + INTERFACE_QUERY + CORE_EDISON_RESOURCES
+ };
+
+ private List<OcWorkerListener> mListeners;
+
+ public OcWorker(Context context) {
+ if (LOCAL_LOGV) Log.v(TAG, "OcWorker() constructor");
+
+ mContext = context;
+ this.mListeners = new ArrayList<>();
+ }
+
+ /**
+ * Set up our Handler and Looper, then initialize the OIC platform and
+ * start processing messages as they arrive.
+ */
+ public void run() {
+ if (LOCAL_LOGV) Log.v(TAG, "run()");
+
+ Looper.prepare();
+ this.initHandlers(); // set up our message handler
+ this.ocInit(); // init the OIC layer including calling ConfigurePlatform
+ Looper.loop();
+ }
+
+ /**
+ * Registers a listener for OcWorker events.
+ *
+ * @see org.iotivity.guiclient.OcWorkerListener
+ */
+ public void registerListener(OcWorkerListener listener) {
+ if (LOCAL_LOGV) Log.v(TAG, "registerListener()");
+
+ if(null != this.mListeners) {
+ this.mListeners.add(listener);
+ } else {
+ Log.e(TAG, "registerListener(): null mListeners list; not adding listener!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * The Resource discovery external API
+ */
+ public void doDiscoverResources() {
+ if (LOCAL_LOGV) Log.v(TAG, "doDiscoverResources()");
+
+ if(null != this.mDoMsgHandler) {
+ this.mDoMsgHandler.obtainMessage(
+ DO_DISCOVER_RESOURCES.ordinal()).sendToTarget();
+ } else {
+ Log.e(TAG, "doDiscoverResources(): null mDoMsgHandler; not discovering resources!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * The GetResource external API
+ */
+ public void doGetResource(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "doGetResource()");
+
+ if(null != this.mDoMsgHandler) {
+ this.mDoMsgHandler.obtainMessage(
+ DO_GET_RESOURCE.ordinal(), resourceInfo).sendToTarget();
+ } else {
+ Log.e(TAG, "doPutResource(): null mDoMsgHandler; not putting resource!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * The PutResource external API
+ */
+ public void doPutResource(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "doPutResource()");
+
+ if(null != this.mDoMsgHandler) {
+ this.mDoMsgHandler.obtainMessage(
+ DO_PUT_RESOURCE.ordinal(), resourceInfo).sendToTarget();
+ } else {
+ Log.e(TAG, "doPutResource(): null mDoMsgHandler; not putting resource!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * The Clear Resources external API
+ */
+ public void doClearResources() {
+ if (LOCAL_LOGV) Log.v(TAG, "doClearResources()");
+
+ if(null != this.mDoMsgHandler) {
+ this.mDoMsgHandler.obtainMessage(
+ DO_CLEAR_RESOURCES.ordinal()).sendToTarget();
+ } else {
+ Log.e(TAG, "doClearResources(): null mDoMsgHandler; not clearing resources!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * Set up handlers
+ */
+ private void initHandlers() {
+ if (LOCAL_LOGV) Log.v(TAG, "initHandler()");
+
+ this.mDoMsgHandler = new Handler() {
+ public void handleMessage(Message msg) {
+ Log.d(TAG, String.format("mDoMsgHandler.handleMessage(%s)", msg.toString()));
+ // process incoming messages here
+ OCW_IN_MSG type = fromInt(msg.what);
+ switch(type) {
+ case DO_TEST:
+ break;
+ case DO_DISCOVER_RESOURCES:
+ discoverResources();
+ break;
+ case DO_CLEAR_RESOURCES:
+ clearResourceInfoList();
+ break;
+ case DO_GET_RESOURCE:
+ getResourceAttributes((OcResourceInfo)msg.obj);
+ break;
+ case DO_PUT_RESOURCE:
+ putResourceAttributes((OcResourceInfo)msg.obj);
+ break;
+ case DO_OBSERVE_RESOURCE:
+ break;
+ case DO_STOP_OBSERVING_RESOURCE:
+ break;
+ default:
+ Log.e(TAG, "unknown msg.what in handler");
+ break;
+ }
+ }
+ };
+
+ this.mOcEventHandler = new Handler() {
+ public void handleMessage(Message msg) {
+ Log.d(TAG, String.format("mOcEventHandler.handleMessage(%s)", msg.toString()));
+ // process incoming messages here
+ OC_EVENT type = OC_EVENT.fromInt(msg.what);
+ switch(type) {
+ case OIC_RESOURCE_FOUND:
+ handleNewResourceFound((OcResource)msg.obj);
+ break;
+ case OIC_RESOURCE_CHANGED:
+ handleResourceInfoChange((OcResourceInfo)msg.obj);
+ break;
+ }
+ }
+ };
+ }
+
+ /**
+ * Get the attributes on resourceInfo.
+ *
+ * @param resourceInfo
+ */
+ private void getResourceAttributes(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "getResourceAttributes()");
+
+ // find the matching resource in our resourceList
+ OcResourceInfo existingResource = this.selectResourceInfoByHostAndUri(
+ resourceInfo.getHost() + resourceInfo.getUri());
+ if(null != existingResource) {
+ existingResource.doOcGet();
+ } else {
+ Log.e(TAG, "getResourceAttributes(): could not find target resource.");
+ }
+ // Done. Later, the onGet listener in the OcResourceInfo object will notify us of a change
+ // via our onResourceChanged() method
+ }
+
+ /**
+ * For each attribute in the resourceInfo.mAttributes, put the attribute value to the
+ * Resource.
+ *
+ * @param resourceInfo
+ */
+ private void putResourceAttributes(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "putResourceAttributes()");
+
+ // find the matching resource in our resourceList
+ OcResourceInfo existingResource = this.selectResourceInfoByHostAndUri(
+ resourceInfo.getHost() + resourceInfo.getUri());
+ if(null != existingResource) {
+ // for each attribute in resourceInfo, put that attribute to the resource
+ for(OcAttributeInfo attribute : resourceInfo.getAttributes()) {
+ if(false == attribute.isReadOnly()) {
+ existingResource.doOcPut(attribute);
+ }
+ }
+ } else {
+ Log.e(TAG, "putResourceAttributes(): could not find target resource.");
+ }
+ // Done. later, the onPut listener in the OcResourceInfo object will notify us of a change
+ // via our onResourceChanged() method
+ }
+
+ /**
+ * Because this callback is called on a JNI layer thread, don't do work here.
+ * Instead, create a "found resource" message and send to OcWorker's message queue,
+ * Our looper/handler then calls handleNewResource on our own worker thread.
+ *
+ * Also note that this method must be thread safe because it can be called by
+ * multiple concurrent native threads.
+ *
+ * @param resource
+ */
+ private Object onResourceFoundLock = new Object(); // not strictly necessary with this impl.,
+ // but clears up Log message readability.
+ @Override
+ public void onResourceFound(OcResource resource) {
+ synchronized (onResourceFoundLock) {
+ if (LOCAL_LOGV) Log.v(TAG, "onResourceFound()");
+ if (LOCAL_LOGV) Log.v(TAG, "host: " + resource.getHost());
+ if (LOCAL_LOGV) Log.v(TAG, "uri: " + resource.getUri());
+ if (LOCAL_LOGV) Log.v(TAG, "is observable: " + resource.isObservable());
+
+ this.mOcEventHandler.obtainMessage(OC_EVENT.OIC_RESOURCE_FOUND.ordinal(),
+ resource).sendToTarget();
+ }
+ }
+
+ /**
+ * Handles the internal NEW_RESOURCE_FOUND event, typically engueued on "onResourceFound".
+ * Creates a new OcResourceInfo object to wrap the new OcResource and store other info.
+ *
+ * @param resource the OcResource object
+ */
+ private void handleNewResourceFound(OcResource resource) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("handleNewResourceFound(%s)",
+ resource.toString()));
+
+ OcResourceInfo ri =
+ this.selectResourceInfoByHostAndUri(resource.getHost() + resource.getUri());
+
+ // before notifying listeners, update our own internal OcResourceInfo list
+ if(null != mOcResourceInfoList) {
+ // check for pre-existing duplicate before adding
+ if(null == ri) {
+ if (LOCAL_LOGV) Log.v(TAG, "handleNewResourceFound(): ri is new; adding.");
+ // if not found, create new info object
+ ri = new OcResourceInfo(resource, this);
+ // register as a listener to the newly created OcResourceInfo
+ ri.registerListener(this);
+ // kick off a get to fill in attributes
+ ri.doOcGet();
+ // add the info object to our list
+ mOcResourceInfoList.add(ri);
+ }
+ }
+ // notify listeners
+ for(OcWorkerListener l : this.mListeners) {
+ l.onResourceFound(ri);
+ }
+ }
+
+ /**
+ * The "listener" callback from the OcResourceInfo class.
+ * Called by the OcResourceInfo object using the native callback thread.
+ * We use this callback to post an event to our queue so that the work
+ * is serialized with other incoming events, and executed on our worker thread.
+ *
+ * Also note that this method must be thread safe because it could be called by
+ * one of many OcResourceInfo objects on separate native threads.
+ *
+ * @param resourceInfo
+ */
+ private Object onResourceInfoChangedLock = new Object();
+ @Override
+ public void onResourceInfoChanged(OcResourceInfo resourceInfo) {
+
+ synchronized (onResourceInfoChangedLock) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("resourceInfoChanged(%s)",
+ resourceInfo.toString()));
+
+ // this is a result of a callback (i.e. onGetCompleted, onPut, onObserve)
+ // so we post a message to our queue to transfer the work to our own thread
+ this.mOcEventHandler.obtainMessage(OC_EVENT.OIC_RESOURCE_CHANGED.ordinal(),
+ resourceInfo).sendToTarget();
+ }
+ }
+
+ /**
+ * Handle our internal event that is enqueued when a resource is found.
+ *
+ * @param resourceInfo
+ */
+ private void handleResourceInfoChange(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "handleResourceInfoChange()");
+
+ // notify listeners
+ for(OcWorkerListener l : this.mListeners) {
+ l.onResourceChanged(resourceInfo);
+ }
+ }
+
+ /**
+ * Complete OIC-related initialization, including configuring the platform
+ */
+ private void ocInit() {
+ if (LOCAL_LOGV) Log.v(TAG, "ocInit()");
+
+ // OIC initialization
+ mOcResourceInfoList = new ArrayList<>();
+
+ this.configurePlatform();
+ }
+
+ /**
+ * Configures the OIC platform.
+ */
+ private void configurePlatform() {
+ if (LOCAL_LOGV) Log.v(TAG, "configurePlatform()");
+
+ PlatformConfig cfg = new PlatformConfig(
+ mContext,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+
+ Log.d(TAG, "configurePlatform(): calling OcPlatform.Configure()");
+ OcPlatform.Configure(cfg);
+ }
+
+ /**
+ * Search mOcResourceInfo list for a resource whose Host and Uri concatenated
+ * matches the param passed, and return it.
+ *
+ * @param resourceHostAndUri
+ * @return OcResourceInfo with Host and Uri matching resourceHostAndUri, or null if
+ * no such OcResourceInfo exists in mOcResourceInfoList
+ */
+ private OcResourceInfo selectResourceInfoByHostAndUri(String resourceHostAndUri) {
+ if (LOCAL_LOGV) Log.v(TAG, "selectResourceByHostAndUri()");
+
+ boolean found = false;
+ OcResourceInfo retVal = null;
+
+ for(OcResourceInfo ri : mOcResourceInfoList) {
+ if(!found) {
+ String s = ri.getHost() + ri.getUri();
+ if (resourceHostAndUri.equalsIgnoreCase(s)) {
+ retVal = ri;
+ found = true;
+ }
+ }
+ }
+ if(!found) {
+ Log.v(TAG, "selectResourceByHostAndUri(): no resource found matching HostAndUri "
+ + resourceHostAndUri);
+ }
+
+ return retVal;
+ }
+
+ /**
+ * Finds OIC Resources matching known patterns.
+ *
+ * @see org.iotivity.guiclient.OcProtocolStrings
+ */
+ private void discoverResources() {
+ if (LOCAL_LOGV) Log.v(TAG, "discoverResources()");
+
+ try {
+ for (String s : mOcFindQueries) {
+ Log.d(TAG, String.format("discoverResources(): Calling OcPlatform.findResource(%s)", s));
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + s,
+ OcConnectivityType.IPV4,
+ this);
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * Clear the ResourceInfoList
+ */
+ private void clearResourceInfoList() {
+ if (LOCAL_LOGV) Log.v(TAG, "clearResourceInfoList()");
+
+ this.mOcResourceInfoList.clear();
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.os.Handler;
+
+import java.util.List;
+
+/**
+ * Applications wishing to use the OcWorker object must implement this interface to
+ * receive notification of OcWorker's ResourceFound and ResourceChanged events.
+ *
+ * @see org.iotivity.guiclient.OcWorker
+ */
+public interface OcWorkerListener {
+
+ /**
+ * Called whenever a new Resource is discovered.
+ *
+ * Note that the calling thread for this callback is not a UI thread. OcWorkerListeners
+ * with UI functionality should post a message to their own UI thread, or similar action.
+ *
+ * @param resourceInfo
+ */
+ public void onResourceFound(final OcResourceInfo resourceInfo);
+
+ /**
+ * Called whenever a previously-discovered Resource changes, e.g. as a result of Put,
+ * or Observe callbacks.
+ *
+ * Note that the calling thread for this callback is not a UI thread. OcWorkerListeners
+ * with UI functionality should post a message to their own UI thread, or similar action.
+ *
+ * @param resourceInfo
+ */
+ public void onResourceChanged(final OcResourceInfo resourceInfo);
+
+}
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_height="wrap_content"
+ android:layout_width="56dp"
+ android:minWidth="56dp"
+ android:clickable="true">
+ <ProgressBar android:id="@+id/find_resource_progress_bar"
+ android:layout_width="32dp"
+ android:layout_height="32dp"
+ android:layout_gravity="center"
+ android:clickable="true"/>
+</FrameLayout>
\ No newline at end of file
--- /dev/null
+<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_horizontal_margin"
+ android:paddingBottom="@dimen/activity_horizontal_margin"
+ tools:context=".MainActivity">
+
+ <ExpandableListView
+ android:id="@+id/expandableResourceListView"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentRight="true"
+ android:layout_alignParentTop="true"
+ android:layout_marginTop="10dp"
+ >
+
+ </ExpandableListView>
+
+</RelativeLayout>
+
+
+ <!--<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"-->
+ <!--xmlns:tools="http://schemas.android.com/tools"-->
+ <!--android:id="@+id/container"-->
+ <!--android:layout_width="match_parent"-->
+ <!--android:layout_height="match_parent"-->
+ <!--tools:context=".MainActivity"-->
+ <!--tools:ignore="MergeRootFrame" />-->
--- /dev/null
+<?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">
+
+ <ImageView android:id="@+id/attribute_icon_id"
+ android:layout_width="50dp"
+ android:layout_height="50dp"
+ android:layout_marginLeft="40dp"
+ android:src="@drawable/attribute_icon"/>
+
+ <TextView android:id="@+id/attribute_name_id"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:inputType="textNoSuggestions"
+ android:text="@string/attribute_name_not_set"
+ android:textSize="14dp"
+ android:clickable="true"
+ android:cursorVisible="false"
+ android:focusable="false"
+ android:focusableInTouchMode="false"
+ android:layout_toRightOf="@+id/attribute_icon_id"
+ />
+
+ <TextView android:id="@+id/attribute_value_id"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingLeft="10dp"
+ android:inputType="textNoSuggestions"
+ android:text="@string/attribute_value_not_set"
+ android:textSize="14dp"
+ android:clickable="false"
+ android:cursorVisible="false"
+ android:focusable="false"
+ android:focusableInTouchMode="false"
+ android:layout_toRightOf="@+id/attribute_name_id"
+ />
+
+ <LinearLayout android:id="@+id/attribute_specific_view"
+ android:orientation="horizontal"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignLeft="@+id/attribute_name_id"
+ android:layout_alignParentRight="true"
+ android:layout_below="@+id/attribute_name_id"
+ android:layout_toRightOf="@+id/attribute_icon_id">
+
+ <Switch android:id="@+id/attribute_switch"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:text="@string/unnamed_switch"
+ android:textSize="12dp"
+ />
+
+ </LinearLayout>
+
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<?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">
+
+ <ImageView android:id="@+id/attribute_icon_id"
+ android:layout_width="50dp"
+ android:layout_height="50dp"
+ android:layout_marginLeft="40dp"
+ android:src="@drawable/attribute_icon"/>
+
+ <TextView android:id="@+id/attribute_name_id"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:inputType="textNoSuggestions"
+ android:text="@string/attribute_name_not_set"
+ android:textSize="14dp"
+ android:clickable="true"
+ android:cursorVisible="false"
+ android:focusable="false"
+ android:focusableInTouchMode="false"
+ android:layout_toRightOf="@+id/attribute_icon_id"
+ />
+
+ <TextView android:id="@+id/attribute_value_id"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingLeft="10dp"
+ android:inputType="textNoSuggestions"
+ android:text="@string/attribute_value_not_set"
+ android:textSize="14dp"
+ android:clickable="false"
+ android:cursorVisible="false"
+ android:focusable="false"
+ android:focusableInTouchMode="false"
+ android:layout_toRightOf="@+id/attribute_name_id"
+ />
+
+ <LinearLayout android:id="@+id/attribute_specific_view"
+ android:orientation="horizontal"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignLeft="@+id/attribute_name_id"
+ android:layout_alignParentRight="true"
+ android:layout_below="@+id/attribute_name_id"
+ android:layout_toRightOf="@+id/attribute_icon_id">
+
+ <ProgressBar android:id="@+id/attribute_progress_bar"
+ style="?android:attr/progressBarStyleHorizontal"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"/>
+
+ </LinearLayout>
+
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<?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">
+
+ <ImageView android:id="@+id/attribute_icon_id"
+ android:layout_width="50dp"
+ android:layout_height="50dp"
+ android:layout_marginLeft="40dp"
+ android:src="@drawable/attribute_icon"/>
+
+ <TextView android:id="@+id/attribute_name_id"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:inputType="textNoSuggestions"
+ android:text="@string/attribute_name_not_set"
+ android:textSize="14dp"
+ android:clickable="true"
+ android:cursorVisible="false"
+ android:focusable="false"
+ android:focusableInTouchMode="false"
+ android:layout_toRightOf="@+id/attribute_icon_id"
+ />
+
+ <TextView android:id="@+id/attribute_value_id"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingLeft="10dp"
+ android:inputType="textNoSuggestions"
+ android:text="@string/attribute_value_not_set"
+ android:textSize="14dp"
+ android:clickable="false"
+ android:cursorVisible="false"
+ android:focusable="false"
+ android:focusableInTouchMode="false"
+ android:layout_toRightOf="@+id/attribute_name_id"
+ />
+
+ <LinearLayout android:id="@+id/attribute_specific_view"
+ android:orientation="horizontal"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignLeft="@+id/attribute_name_id"
+ android:layout_alignParentRight="true"
+ android:layout_below="@+id/attribute_name_id"
+ android:layout_toRightOf="@+id/attribute_icon_id">
+
+ <SeekBar android:id="@+id/attribute_slider"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:text="@string/unnamed_slider"
+ android:textSize="12dp"
+ />
+
+ </LinearLayout>
+
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<?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">
+
+ <ImageView android:id="@+id/resource_icon_id"
+ android:layout_width="50dp"
+ android:layout_height="50dp"
+ android:layout_marginLeft="20dp"/>
+
+ <TextView android:id="@+id/resource_name_id"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:inputType="textNoSuggestions"
+ android:text="@string/resource_name_not_set"
+ android:textSize="16dp"
+ android:clickable="true"
+ android:cursorVisible="false"
+ android:focusable="false"
+ android:focusableInTouchMode="false"
+ android:layout_toRightOf="@+id/resource_icon_id"
+ />
+
+ <TextView android:id="@+id/resource_description_id"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingLeft="10dp"
+ android:inputType="textNoSuggestions"
+ android:text="@string/resource_description_not_set"
+ android:textSize="14dp"
+ android:clickable="false"
+ android:cursorVisible="false"
+ android:focusable="false"
+ android:focusableInTouchMode="false"
+ android:layout_below="@+id/resource_name_id"
+ android:layout_toRightOf="@+id/resource_icon_id"
+ />
+
+ <ImageView android:id="@+id/observing_icon_id"
+ android:layout_width="50dp"
+ android:layout_height="50dp"
+ android:layout_alignParentRight="true"
+ />
+
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<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=".MainActivity">
+ <item android:id="@+id/action_settings" android:title="@string/action_settings"
+ android:orderInCategory="100" app:showAsAction="never" />
+ <item android:id="@+id/action_test" android:title="@string/action_test"
+ android:orderInCategory="100" app:showAsAction="never" />
+ <item android:id="@+id/action_refresh"
+ android:icon="@drawable/ic_action_refresh"
+ android:title="@string/discover_resources"
+ android:alphabeticShortcut="r"
+ app:showAsAction="always" />
+ <item android:id="@+id/action_discard"
+ android:icon="@drawable/ic_action_discard"
+ android:title="@string/action_discard"
+ android:alphabeticShortcut="d"
+ app:showAsAction="always"/>
+</menu>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+ <!--
+ Layout alias to replace the single-pane version of the layout with a
+ two-pane version on Large screens.
+
+ For more on layout aliases, see:
+ http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters
+ -->
+
+</resources>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+ <!--
+ Layout alias to replace the single-pane version of the layout with a
+ two-pane version on Large screens.
+
+ For more on layout aliases, see:
+ http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters
+ -->
+
+</resources>
\ No newline at end of file
--- /dev/null
+<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>
--- /dev/null
+<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">8dp</dimen>
+</resources>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+ <!--
+ Layout alias to replace the single-pane version of the layout with a
+ two-pane version on Large screens.
+
+ For more on layout aliases, see:
+ http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters
+ -->
+
+</resources>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">IoTivity Client Demo</string>
+ <string name="action_settings">Settings</string>
+ <string name="action_discard">Clear Items</string>
+ <string name="action_test">Developer Test Action</string>
+ <string name="edit_input">default-string-from-xml</string>
+ <string name="ok">OK</string>
+ <string name="cancel">Cancel</string>
+ <string name="attribute_name_not_set">Attribute Name not set</string>
+ <string name="attribute_value_not_set">Attribute Value not set</string>
+ <string name="resource_name_not_set">Resource Name not set</string>
+ <string name="resource_description_not_set">Resource Description not set</string>
+ <string name="unnamed_switch">Unnamed Switch</string>
+ <string name="unnamed_slider">Unnamed Slider</string>
+ <string name="oc_light_switch_toggle_text">Turn Light On/Off:</string>
+ <string name="discover_resources">Discover Resources</string>
+ <string name="no_resource_selected">No Resource Selected</string>
+ <string name="oc_led_switch_toggle_text">Turn LED on/off</string>
+ <string name="ui_resource_label_light">SimpleServer Light</string>
+ <string name="ui_resource_label_ambient_light_sensor">Edison Ambient Light Sensor</string>
+ <string name="ui_resource_label_platform_led">Edison Platform LED</string>
+ <string name="ui_resource_label_room_temperature_sensor">Edison Room Temp Sensor</string>
+ <string name="ui_attribute_label_ambient_light_sensor_reading">Ambient Light Level:</string>
+ <string name="ui_attribute_label_light_dimmer">Light Dimmer:</string>
+ <string name="ui_attribute_label_light_switch">Light Switch:</string>
+ <string name="ui_attribute_label_led_switch">LED switch:</string>
+ <string name="ui_attribute_label_room_temperature_sensor_reading">Temperature Reading:</string>
+</resources>
--- /dev/null
+<resources>
+
+ <!-- Base application theme. -->
+ <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
+ <!-- Customize your theme here. -->
+ </style>
+
+</resources>
-include ':simpleserver', ':simpleclient', ':message',':fridgeserver',':fridgeclient'
+include ':simpleserver', ':simpleclient', ':message', ':fridgeserver', ':fridgeclient', ':guiclient'
help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device (For Arduino)', device_name, None, None),)
+AddOption('--prefix',
+ dest='prefix',
+ type='string',
+ nargs=1,
+ action='store',
+ metavar='DIR',
+ help='installation prefix')
+
######################################################################
# Platform(build target) specific options: SDK/NDK & toolchain
######################################################################
tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
)
else:
- env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os)
+ env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os, PREFIX = GetOption('prefix'))
Help(help_vars.GenerateHelpText(env))
Alias(name, i_n)
env.AppendUnique(TS = [name])
+def __installlib(ienv, targets, name):
+ user_prefix = env.get('PREFIX')
+ if user_prefix:
+ i_n = ienv.Install(user_prefix + '/lib', targets)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+ ienv.Alias("install", i_n)
+
+def __installbin(ienv, targets, name):
+ user_prefix = env.get('PREFIX')
+ if user_prefix:
+ i_n = ienv.Install(user_prefix + '/bin', targets)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+ ienv.Alias("install", i_n)
+
def __append_target(ienv, name, targets = None):
if targets:
env.Alias(name, targets)
env.AddMethod(__src_to_obj, 'SrcToObj')
env.AddMethod(__append_target, 'AppendTarget')
env.AddMethod(__install, 'InstallTarget')
+env.AddMethod(__installlib, 'UserInstallTargetLib')
+env.AddMethod(__installbin, 'UserInstallTargetBin')
env.SetDir(env.GetLaunchDir())
env['ROOT_DIR']=env.GetLaunchDir()+'/..'
SConscript('tools/UnpackAll.py')
+# tinycbor build/fetch
+SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'tinycbor', 'SConscript'))
+
env.AddMethod(__prepare_lib, "PrepareLib")
env.AddMethod(__configure, "Configure")
env.AddMethod(__download, "Download")
--- /dev/null
+#!/bin/bash
+
+# Fail script on any failure
+set -e
+
+# Move to script direotory
+pushd `dirname $0` > /dev/null
+
+rm -rf docs
+
+# JavaDoc now... from Uze's script
+ANDROID_JAR="$ANDROID_HOME/platforms/android-21/android.jar"
+
+if [ ! -e "$ANDROID_JAR" ]; then
+ echo "Android platform not found. Expected '$ANDROID_JAR'"
+ exit 1
+fi
+
+BASE_PATH="android/android_api/base/src/main/java/"
+BASE_PKG="org.iotivity.base"
+
+TM_PATH="service/things-manager/sdk/java/src/"
+TM_PKG="org.iotivity.service.tm"
+
+SSM_PATH="service/soft-sensor-manager/SDK/java/"
+SSM_PKG="org.iotivity.service.ssm"
+
+PPM_PATH="service/protocol-plugin/plugin-manager/src/Android/src"
+PPM_PKG="service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/PluginManager.java service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/Plugin.java"
+# PPM_PKG="org.iotivity.service.ppm"
+
+javadoc -splitindex \
+ -d ./docs/java \
+ -sourcepath $BASE_PATH:$TM_PATH:$SSM_PATH $BASE_PKG $TM_PKG $SSM_PKG $PPM_PKG \
+ -classpath $ANDROID_JAR
+
+# Doxygen now...
+# NOTE: For now this is a workaround since I am ready to modify the doxygen setup
+pushd resource/docs > /dev/null
+doxygen
+
+# Check for warnings or errors
+if [ -s doxygen.log ]; then
+ echo "Errors running doxygen. Review doxygen.log"
+ exit 2
+fi
+
+popd > /dev/null
+rm -rf docs/cxx
+mv resource/docs/docs/html docs/cxx
+
+popd > /dev/null
{
m_resourceMap.clear();
- OC::OCPlatform::findResource("", OC_WELL_KNOWN_QUERY, CT_DEFAULT, m_findCB);
+ OC::OCPlatform::findResource("", OC_RSRVD_WELL_KNOWN_URI, CT_DEFAULT, m_findCB);
}
void MiddleClient::foundOCResource(shared_ptr<OCResource> resource)
return LR_Timeout;
}
- std::string jsonRep = wreq->m_rep.getJSONRepresentation();
+ std::string jsonRep ;//= wreq->m_rep.getJSONRepresentation();
//ss << jsonRep << endl;
printJSONAsTable(jsonRep);
return LR_OK;
if (!m_observer)
return;
cout << "cb " << eCode << " " << sequenceNumber << '\n';
- cout << rep.getJSONRepresentation() << "\n";
+ //cout << rep.getJSONRepresentation() << "\n";
}
ParseState LineInput::finishElem(char*& e, elements_t& elems)
{
}
+Middle::~Middle()
+{
+ delete m_client;
+ delete m_server;
+ delete m_lineInput;
+ delete m_restInput;
+}
+
void Middle::init()
{
{
public:
Middle();
+ ~Middle();
void init();
void run(int argc, char* argv[]);
using namespace std;
#define BUFLEN 10000
-#define MAX_CONNS 5
static bool enableDebug = false; // set to true to print debug messages
RestInput::RestInput(LineInput *lineInput) : m_lineInput(lineInput)
{
m_data = (char*)malloc(BUFLEN);
- m_thread = new std::thread[MAX_CONNS];
m_threadCount = 0;
}
+RestInput::~RestInput()
+{
+ free(m_data);
+ close(m_sockfd);
+}
+
bool RestInput::init()
{
m_sockfd = socket(AF_INET, SOCK_STREAM, 0);
return;
}
int n = read(connfd, m_data, BUFLEN);
+ close(connfd);
if (n < 0) {
cerr << "Failed to read from socket" << endl;
return;
class RestInput
{
+ static const int MAX_CONNS = 5;
public:
RestInput(LineInput *lineInput);
+ ~RestInput();
bool init();
void startAccept(int &sockfd);
void startThread();
int m_sockfd, m_port, m_threadCount;
struct sockaddr_in m_serverAddr;
char *m_data;
- std::thread *m_thread;
+ std::thread m_thread[MAX_CONNS];
};
#endif // RESTINPUT_H
+++ /dev/null
-#For Yocto builds, set OS=yocto as a command-line argument to scons once
-#the Yocto toolchain is installed and configured.
-
-#For Linux builds, set the following two variables:
-#Set OIC_RESOURCE_PATH to the root of oic-resource on Ubuntu.
-
-OIC_RESOURCE_PATH = '../..'
-
-#Set OIC_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so,
-#liboc_logger.so and libcoap.so.
-
-OIC_LIBS_PATH = '../../out/linux/x86_64/release'
-
-env = DefaultEnvironment()
-target_os = ARGUMENTS.get("OS", "linux").lower()
-output_dir = env.GetLaunchDir() + "/out/" + target_os
-env.VariantDir(output_dir, env.GetLaunchDir(), duplicate=0)
-env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
-env.AppendUnique(LINKFLAGS = ['-pthread'])
-env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap'])
-env.Program(output_dir + '/OICMiddle', [output_dir + '/OICMiddle.cpp',
- output_dir + '/Client.cpp',
- output_dir + '/Server.cpp',
- output_dir + '/WrapResource.cpp',
- output_dir + '/LineInput.cpp',
- output_dir + '/RestInput.cpp'])
-
-if target_os == "yocto":
- '''
- This code injects Yocto cross-compilation flags into scons' default environment
- in order to invoke the relevant tools while performing a build.
- '''
- import os.path, re
- sdk_root = ''
- try:
- CC = os.environ['CC']
- sdk_root = re.search(r'--sysroot=\S+', CC).group().split('=')[1]
- 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])
- env.AppendUnique(CPPPATH = [
- sdk_root + '/usr/include/oic/',
- sdk_root + '/usr/include/oic/stack/',
- sdk_root + '/usr/include/oic/ocsocket/',
- sdk_root + '/usr/include/oic/oc_logger/',
- ])
- except:
- print "ERROR configuring Yocto cross-toolchain environment."
- Exit(1)
-elif target_os == "linux":
- if OIC_RESOURCE_PATH == '' or OIC_LIBS_PATH == '':
- print "ERROR Please set both OIC_RESOURCE_PATH and OIC_LIBS_PATH in SConstruct"
- Exit(1)
- env.AppendUnique(CPPPATH = [
- OIC_RESOURCE_PATH + '/resource/include',
- OIC_RESOURCE_PATH + '/resource/csdk/stack/include',
- OIC_RESOURCE_PATH + '/resource/csdk/ocsocket/include',
- OIC_RESOURCE_PATH + '/resource/oc_logger/include',
- ])
- env.AppendUnique(LIBPATH = [OIC_LIBS_PATH])
-else:
- print "ERROR ", target_os, " is an unsupported target"
- Exit(1)
{
string sep = "\":";
string anchor = "\"rep\":{";
- string json = wreq->m_rep.getJSONRepresentation();
+ string json;// = wreq->m_rep.getJSONRepresentation();
string name, type, value, next;
size_t r, e, e1, s, c;
--- /dev/null
+//******************************************************************
+//
+// This example includes
+// - Server application for Edison which demonstrates Iotivity server
+// capabilities through the integration of an add-on breadboard that
+// hosts temperature, ambient light and LED resources.
+// - Client application to test server functionality, discovering and
+// communicating with these resources.
+//
+// See complete documentation at
+// https://wiki.iotivity.org/_media/oicsensorboardreadme.pdf
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
void IoTClient::findResource()
{
- string coap_multicast_discovery = string(OC_WELL_KNOWN_QUERY "?if=" EDISON_RESOURCE_INTERFACE);
- OCPlatform::findResource("", coap_multicast_discovery.c_str(), OC_ALL, m_resourceDiscoveryCallback,
+ string coap_multicast_discovery = string(OC_RSRVD_WELL_KNOWN_URI "?if=" EDISON_RESOURCE_INTERFACE);
+ OCPlatform::findResource("", coap_multicast_discovery.c_str(), CT_DEFAULT, m_resourceDiscoveryCallback,
OC::QualityOfService::LowQos);
}
{
double value;
rep.getValue(TEMPERATURE_RESOURCE_KEY, value);
- cout << "Observing TemperatureSensor: Current temperature reading is " << value << endl;
+ cout << "Observing TemperatureSensor: Current temperature reading in Celsius is " << value << endl;
cout << "Sequence number: " << sequenceNumber << endl;
}
else
{
double value;
representation.getValue(TEMPERATURE_RESOURCE_KEY, value);
- cout << endl << endl << "Current temperature reading: " << value << endl;
+ cout << endl << endl << "Current temperature reading in Celsius: " << value << endl;
}
else {
cerr << endl << endl << "Error in GET response from temperature sensor resource" << endl;
#define ONBOARD_LED_PIN 13
#define TEMPERATURE_AIO_PIN 0
#define LIGHT_SENSOR_AIO_PIN 2
+#define SAMPLE_NUM 5
namespace Sensors
{
mraa_gpio_write(led_gpio, on); // Writes into GPIO
}
-inline float GetTemperatureInC()
+inline float GetAverageTemperatureRaw()
{
- float ret = 0;
if (tmp_aio == NULL)
{
tmp_aio = mraa_aio_init(TEMPERATURE_AIO_PIN); // initialize pin 0
}
- if (tmp_aio != NULL)
- {
- uint16_t adc_value = mraa_aio_read(tmp_aio); // read the raw value
- //convert reading to temperature
- float beta = 4090.0; //the beta of the thermistor, magic number
- ret = beta / (log((4095.0 * 10 / adc_value - 10) / 10) + beta / 298.0) - 273.0;
- }
+
+ uint16_t adc_value = 0;
+ for (int i=0; i< SAMPLE_NUM; i++)
+ adc_value += mraa_aio_read(tmp_aio); // read the raw value
+
+ float average = (float)adc_value/SAMPLE_NUM;
+ cout << "Temperature reading raw ..." << average << endl;
+
+ return average;
+}
+
+inline float GetTemperatureInC()
+{
+ // Temperature calculation using simpilfy Steinhart-Hart equation
+ //
+ // 1/T = 1/T0 + 1/beta*ln (R/R0)
+ //
+ // where T0 = 25C room temp, R0 = 10000 ohms
+ //
+ float beta = 4090.0; //the beta of the thermistor, magic number
+ float t_raw = GetAverageTemperatureRaw();
+ float R = 1023.0/t_raw -1; //
+ R = 10000.0/R; // 10K resistor divider circuit
+
+ float T1 = log(R/10000.0)/beta; // natural log
+ float T2 = T1 + 1.0/298.15; // room temp 25C= 298.15K
+ float ret = 1.0/T2 - 273.0;
+
return ret;
}
#include <signal.h>
#include <thread>
#include <functional>
+
#include "server.h"
#include "sensors.h"
#include "namedefs.h"
EXTDIR=$(pwd)
-# Check for cereal existence
-if [ ! -d "cereal" ]; then
- git clone https://github.com/USCiLab/cereal.git cereal
- pushd cereal
- git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245
- git apply ../../resource/patches/cereal_gcc46.patch
- popd
-fi
-
# Pick the preferred version of boost to use
BOOST_MAJOR=1
BOOST_MINOR=57
if [ ! -d "boost" ]; then
cloneBoost
fi
-
- # Determine the
+
+ # Determine the
TOOLCHAIN=${ANDROID_NDK}/toolchains/${TOOLSET}-${VERSION}/prebuilt/${HOST_ARCH}/bin
OLDPATH=$PATH
+++ /dev/null
-######################################################################
-# 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])
--- /dev/null
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+import os
+
+Import('env')
+
+src_dir = env.get('SRC_DIR')
+
+cborDir = os.path.join(src_dir, 'extlibs','tinycbor','tinycbor')
+
+if not os.path.exists(cborDir):
+ print '''
+*********************************** Error: ****************************************
+* Please download cbor using the following command: *
+* $ git clone https://github.com/01org/tinycbor.git extlibs/tinycbor/tinycbor *
+***********************************************************************************
+'''
+ Exit(1)
+
+cbor_src = [
+ os.path.join(cborDir,'src/cborparser.c'),
+ os.path.join(cborDir,'src/cborencoder.c')
+ ]
+
+env['cbor_files'] = cbor_src
+env.AppendUnique(CPPPATH = [os.path.join(cborDir, 'src')])
+
+
env.AppendUnique(TINYDTLS_SRC = tinydtls_src)
if not env.get('RELEASE'):
- if(target_os) not in ['android', 'arduino']:
+ if(target_os) not in ['arduino']:
env.AppendUnique(TINYDTLS_SRC = ['debug.c'])
+ else:
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
else:
env.AppendUnique(CPPDEFINES = ['NDEBUG'])
samples_env.AppendTarget('samples')
env.InstallTarget(libtinydtls, 'libtinydtls');
+env.UserInstallTargetLib(libtinydtls, 'libtinydtls');
target_os = env.get('TARGET_OS')
target_arch = env.get('TARGET_ARCH')
src_dir = env.get('SRC_DIR')
-
-env.SConscript('extlibs/cereal/SConscript')
mkdir ./tmp/packaging
cp -R ./build_common $sourcedir/tmp
cp -R ./examples $sourcedir/tmp
-cp -R ./extlibs/cereal $sourcedir/tmp/extlibs
+cp -R ./extlibs/tinycbor $sourcedir/tmp/extlibs
cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
cp -R ./extlibs/timer $sourcedir/tmp/extlibs
cd $sourcedir/tmp
echo `pwd`
-rm -rf ./extlibs/cereal/cereal/.git*
+rm -rf ./extlibs/tinycbor/tinycbor/.git*
# Initialize Git repository
if [ ! -d .git ]; then
if target_os == 'android':
static_compatibilitylib = compatibilitylib_env.StaticLibrary('compatibility', compatibilitylib_src)
compatibilitylib_env.InstallTarget(static_compatibilitylib, 'libcompatibility')
+ compatibilitylib_env.UserInstallTargetLib(static_compatibilitylib, 'libcompatibility')
commonlib = common_env.StaticLibrary('c_common', common_src)
common_env.InstallTarget(commonlib, 'c_common')
+common_env.UserInstallTargetLib(commonlib, 'c_common')
void *OICMalloc(size_t size);
/**
+ * Re-allocates a block of memory, pointed to by ptr to the size specified
+ * in size. The returned value contains a pointer to the new location, with
+ * all data copied into it. If the new size of the memory-object require movement,
+ * the previous space is freed. If the new size is larger, the newly allocated
+ * area has non-deterministic content. If the space cannot be allocated, the value
+ * ptr is left unchanged.
+ *
+ * @param ptr - Pointer to a block of memory previously allocated by OICCalloc,
+ * OICMalloc, or a previous call to this function. If this value is
+ * NULL, this function will work identically to a call to OICMalloc.
+ *
+ * @param size - Size of the new memory block in bytes, where size > 0
+ *
+ * @return
+ * on success, a pointer to the newly sized memory block
+ * on failure, a null pointer is returned, and the memory pointed to by *ptr is untouched
+ */
+void *OICRealloc(void *ptr, 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.
*
* NOTE: This function is intended to be used internally by the TB Stack.
* It is not intended to be used by applications.
*
- * @param ptr - Pointer to block of memory previously allocated by OCMalloc.
+ * @param ptr - Pointer to block of memory previously allocated by OICMalloc.
* If ptr is a null pointer, the function does nothing.
*/
void OICFree(void *ptr);
#endif
}
+void *OICRealloc(void* ptr, size_t size)
+{
+ if(size == 0)
+ {
+ OICFree(ptr);
+ return NULL;
+ }
+
+#ifdef ENABLE_MALLOC_DEBUG
+ if(ptr == NULL)
+ {
+ return OICMalloc(size);
+ }
+
+ void* newptr = NULL;
+ newptr = realloc(ptr, size);
+ OIC_LOG_V(INFO, TAG, "realloc: ptr=%p, newptr=%p, size=%u", ptr, newptr, size);
+ return ptr;
+#else
+ return realloc(ptr, size);
+#endif
+}
+
void OICFree(void *ptr)
{
#ifdef ENABLE_MALLOC_DEBUG
'../../extlibs/cjson/cJSON.c',
'../../extlibs/timer/timer.c',
OCTBSTACK_SRC + 'ocstack.c',
+ OCTBSTACK_SRC + 'ocpayload.c',
+ OCTBSTACK_SRC + 'ocpayloadparse.c',
+ OCTBSTACK_SRC + 'ocpayloadconvert.c',
OCTBSTACK_SRC + 'occlientcb.c',
OCTBSTACK_SRC + 'ocresource.c',
OCTBSTACK_SRC + 'ocobserve.c',
'ocrandom/src/ocrandom.c'
]
+liboctbstack_src.extend(env['cbor_files'])
+
if target_os in ['arduino','darwin','ios'] :
static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
liboctbstack_env.InstallTarget(static_liboctbstack, 'liboctbstack')
+ liboctbstack_env.UserInstallTargetLib(static_liboctbstack, 'liboctbstack')
else:
static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
shared_liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src)
liboctbstack_env.InstallTarget([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
+ liboctbstack_env.UserInstallTargetLib([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
/**
* @brief Payload information from resource model
*/
-typedef char *CAPayload_t;
+typedef uint8_t *CAPayload_t;
/**
* @brief URI for the OIC base.CA considers relative URI as the URI.
CA_SUCCESS = 200, /**< Success */
CA_CREATED = 201, /**< Created */
CA_DELETED = 202, /**< Deleted */
+ CA_VALID = 203, /**< Valid */
+ CA_CHANGED = 204, /**< Changed */
+ CA_CONTENT = 205, /**< Content */
CA_BAD_REQ = 400, /**< Bad Request */
CA_UNAUTHORIZED_REQ = 401, /**< Unauthorized Request */
CA_BAD_OPT = 402, /**< Bad Option */
CAHeaderOption_t *options; /** Header Options for the request */
uint8_t numOptions; /**< Number of Header options */
CAPayload_t payload; /**< payload of the request */
+ size_t payloadSize; /**< size in bytes of the payload */
CAURI_t resourceUri; /**< Resource URI information **/
} CAInfo_t;
help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)
+AddOption('--prefix',
+ dest='prefix',
+ type='string',
+ nargs=1,
+ action='store',
+ metavar='DIR',
+ help='installation prefix')
+
######################################################################
# Platform(build target) specific options: SDK/NDK & toolchain
######################################################################
tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
)
else:
- env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os)
+ env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os, PREFIX = GetOption('prefix'))
Help(help_vars.GenerateHelpText(env))
Alias(name, i_n)
env.AppendUnique(TS = [name])
+def __installlib(ienv, targets, name):
+ user_prefix = env.get('PREFIX')
+ if user_prefix:
+ i_n = ienv.Install(user_prefix + '/lib', targets)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+ ienv.Alias("install", i_n)
+
+def __installbin(ienv, targets, name):
+ user_prefix = env.get('PREFIX')
+ if user_prefix:
+ i_n = ienv.Install(user_prefix + '/bin', targets)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+ ienv.Alias("install", i_n)
+
def __append_target(ienv, target):
env.AppendUnique(TS = [target])
env.AddMethod(__src_to_obj, 'SrcToObj')
env.AddMethod(__append_target, 'AppendTarget')
env.AddMethod(__install, 'InstallTarget')
+env.AddMethod(__installlib, 'UserInstallTargetLib')
+env.AddMethod(__installbin, 'UserInstallTargetBin')
env.SetDir(env.GetLaunchDir())
env['ROOT_DIR']=env.GetLaunchDir()+'/..'
LOCAL_SRC_FILES = oic_logger.c oic_console_logger.c logger.c \
uarraylist.c uqueue.c \
- cathreadpool_pthreads.c camutex_pthreads.c
+ cathreadpool_pthreads.c camutex_pthreads.c \
+ caremotehandler.c
include $(BUILD_STATIC_LIBRARY)
LOCAL_CFLAGS += -std=c99 -DWITH_POSIX
LOCAL_SRC_FILES = \
- caconnectivitymanager.c caremotehandler.c cainterfacecontroller.c \
+ caconnectivitymanager.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 \
+ $(ADAPTER_UTILS)/cafragmentation.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 \
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
+UTIL_OBJ = caadapterutils.c.o cafragmentation.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
+++ /dev/null
-#/******************************************************************
-# *
-# * 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
-
-
ca_common_src = [
ca_common_src_path + 'uarraylist.c',
ca_common_src_path + 'uqueue.c',
+ ca_common_src_path + 'caremotehandler.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 = [
+ logger_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 = [
+ logger_src = [
ca_common_src_path + 'logger.c',
ca_common_src_path + 'oic_logger.c',
ca_common_src_path + 'oic_console_logger.c'
]
+if env['POSIX_SUPPORTED']:
+ platform_src = [
+ ca_common_src_path + 'cathreadpool_pthreads.c',
+ ca_common_src_path + 'camutex_pthreads.c'
+ ]
+else:
+ platform_src = [
+ ca_common_src_path + 'camutex_noop.c'
+ ]
env.AppendUnique(CA_SRC = ca_common_src)
+env.AppendUnique(CA_SRC = logger_src)
env.AppendUnique(CA_SRC = platform_src)
-
CAEndpoint_t *CACloneEndpoint(const CAEndpoint_t *endpoint);
/**
+ * @brief Allocate CAEndpoint_t instance.
+ * @param flags [IN] Transport flag
+ * @param adapter [IN] Adapter type
+ * @param address [IN] Address
+ * @param port [IN] Port
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAEndpoint_t *CACreateEndpointObject(CATransportFlags_t flags, CATransportAdapter_t adapter,
+ const char *address, uint16_t port);
+/**
* @brief Destroy remote endpoint
* @param endpoint [IN] endpoint information where the data has to be sent
* @return none
*/
-void CADestroyEndpointInternal(CAEndpoint_t *rep);
+void CAFreeEndpoint(CAEndpoint_t *rep);
/**
* @brief Creates a new request information
--- /dev/null
+//******************************************************************
+//
+// 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 with no operation
+ * for Singlethread implementation.
+ */
+
+#include "camutex.h"
+
+/**
+ * TAG
+ * Logging tag for module name
+ */
+#define TAG "UMUTEX"
+
+typedef struct _tagMutexInfo_t
+{
+} ca_mutex_internal;
+
+typedef struct _tagEventInfo_t
+{
+} ca_cond_internal;
+
+/**
+ * @var g_mutexInfo
+ * @brief This is used to return a non NULL value for ca_mutex_new().
+ */
+static ca_mutex_internal g_mutexInfo = { 0 };
+
+/**
+ * @var g_condInfo
+ * @brief This is used to return a non NULL value for ca_cond_new().
+ */
+static ca_cond_internal g_condInfo = { 0 };
+
+ca_mutex ca_mutex_new(void)
+{
+ return &g_mutexInfo;
+}
+
+bool ca_mutex_free(ca_mutex mutex)
+{
+ return true;
+}
+
+void ca_mutex_lock(ca_mutex mutex)
+{
+ return;
+}
+
+bool ca_mutex_trylock(ca_mutex mutex)
+{
+ return true;
+}
+
+void ca_mutex_unlock(ca_mutex mutex)
+{
+ return;
+}
+
+ca_cond ca_cond_new(void)
+{
+ return &g_condInfo;
+}
+
+void ca_cond_free(ca_cond cond)
+{
+ return;
+}
+
+void ca_cond_signal(ca_cond cond)
+{
+ return;
+}
+
+void ca_cond_broadcast(ca_cond cond)
+{
+ return;
+}
+
+void ca_cond_wait(ca_cond cond, ca_mutex mutex)
+{
+ return;
+}
+
+CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseconds)
+{
+ return CA_WAIT_SUCCESS;
+}
+
if (NULL != rep->info.payload)
{
// allocate payload field
- char *temp = OICStrdup(rep->info.payload);
+ uint8_t *temp = OICMalloc(rep->info.payloadSize);
if (NULL == temp)
{
OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
return NULL;
}
+ memcpy(temp, rep->info.payload, rep->info.payloadSize);
// save the payload
clone->info.payload = temp;
}
+ if (NULL != rep->info.resourceUri)
+ {
+ // allocate payload field
+ char *temp = OICStrdup(rep->info.resourceUri);
+ if (NULL == temp)
+ {
+ OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
+
+ CADestroyRequestInfoInternal(clone);
+
+ return NULL;
+ }
+
+ // save the resourceUri
+ clone->info.resourceUri = temp;
+ }
+
return clone;
}
}
// check the result value of response info.
+ // Keep this check in sync with CAResponseResult_t
switch (rep->result)
{
case CA_EMPTY:
case CA_SUCCESS:
case CA_CREATED:
case CA_DELETED:
+ case CA_VALID:
+ case CA_CHANGED:
+ case CA_CONTENT:
case CA_BAD_REQ:
+ case CA_UNAUTHORIZED_REQ:
case CA_BAD_OPT:
+ case CA_FORBIDDEN_REQ:
case CA_NOT_FOUND:
case CA_INTERNAL_SERVER_ERROR:
case CA_RETRANSMIT_TIMEOUT:
break;
default:
- OIC_LOG(ERROR, TAG, "Response status code is invalid number");
+ OIC_LOG_V(ERROR, TAG, "Response code %u is invalid", rep->result);
return NULL;
}
if (NULL != rep->info.payload)
{
// allocate payload field
- char *temp = OICStrdup(rep->info.payload);
+ uint8_t *temp = (uint8_t *) OICMalloc(rep->info.payloadSize);
if (NULL == temp)
{
OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
return NULL;
}
+ memcpy(temp, rep->info.payload, rep->info.payloadSize);
// save the payload
clone->info.payload = temp;
}
+ if (NULL != rep->info.resourceUri)
+ {
+ // allocate payload field
+ char *temp = OICStrdup(rep->info.resourceUri);
+ if (NULL == temp)
+ {
+ OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
+
+ CADestroyResponseInfoInternal(clone);
+
+ return NULL;
+ }
+
+ // save the resourceUri
+ clone->info.resourceUri = temp;
+ }
+
return clone;
}
-void CADestroyEndpointInternal(CAEndpoint_t *rep)
+CAEndpoint_t *CACreateEndpointObject(CATransportFlags_t flags,
+ CATransportAdapter_t adapter,
+ const char *address,
+ uint16_t port)
+{
+ CAEndpoint_t *info = (CAEndpoint_t *)OICCalloc(1, sizeof(CAEndpoint_t));
+ if (NULL == info)
+ {
+ OIC_LOG(ERROR, TAG, "Memory allocation failed !");
+ return NULL;
+ }
+
+ if (address)
+ {
+ OICStrcpy(info->addr, sizeof(info->addr), address);
+ info->addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
+ }
+ info->flags = flags;
+ info->adapter = adapter;
+ info->port = port;
+
+ return info;
+}
+
+void CAFreeEndpoint(CAEndpoint_t *rep)
{
OICFree(rep);
}
// free payload field
OICFree((char *) rep->info.payload);
+ // free uri
+ OICFree(rep->info.resourceUri);
+
OICFree(rep);
}
// free payload field
OICFree((char *) rep->info.payload);
+ // free uri
+ OICFree(rep->info.resourceUri);
+
OICFree(rep);
}
if (NULL == element)
{
- OIC_LOG(DEBUG, TAG, "QueueGetElement : empty, no messages");
return NULL;
}
void CALogPDUData(coap_pdu_t *pdu);
/**
- * @fn CAAdapterCloneEndpoint
- * @brief Create CAEndpoint_t duplicate instance.
- */
-CAEndpoint_t *CAAdapterCloneEndpoint(const CAEndpoint_t *endpoint);
-
-/**
- * @fn CAAdapterFreeEndpoint
- * @brief Deallocate CAEndpoint_t instance.
- */
-void CAAdapterFreeEndpoint(CAEndpoint_t *localEndPoint);
-
-/**
- * @fn CAAdapterCreateEndpoint
- * @brief Allocate CAEndpoint_t instance.
- */
-CAEndpoint_t *CAAdapterCreateEndpoint(CATransportFlags_t flags,
- CATransportAdapter_t adapter, const char *address, uint16_t port);
-
-/**
* @fn CAParseIPv4AddressInternal
* @brief To parse the IP address and port from "ipaddress:port"
* @param ipAddrStr [IN] IP address to be parsed
* @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 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 errorCallback [IN] errorCallback to notify error to connectivity common logic
+ * layer from adapter
* @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, ca_thread_pool_t handle);
+ CANetworkChangeCallback netCallback,
+ CAErrorHandleCallback errorCallback, ca_thread_pool_t handle);
/**
* @brief Starts EDR connectivity adapters. As its peer to peer it doesnot require to start
typedef void (*CAEDRNetworkStatusCallback)(CANetworkStatus_t status);
/**
+ * @brief Callback to notify the error in the EDR adapter
+ * @param remoteAddress [IN] Remote EDR Address
+ * @param serviceUUID [IN] Service UUID of the device
+ * @param data [IN] data containing token, uri and coap data
+ * @param dataLength [IN] length of data
+ * @param result [IN] error code as defined in CAResult_t
+ * @return NONE
+ * @pre Callback must be registered using CAEDRSetPacketReceivedCallback()
+ */
+typedef void (*CAEDRErrorHandleCallback)(const char *remoteAddress, const char *serviceUUID,
+ const void *data, uint32_t dataLength, CAResult_t result);
+
+/**
* @brief Initialize the network monitor module
* @param threadPool [IN] Threadpool Handle
* @return #CA_STATUS_OK or Appropriate error code
void CAEDRSetNetworkChangeCallback(CAEDRNetworkStatusCallback networkStateChangeCallback);
/**
+ * @brief set error callback to notify error in EDR adapter
+ *
+ * @param errorHandleCallback [IN] Callback function to notify the error in the EDR adapter
+ * @return NONE
+ */
+void CAEDRSetErrorHandler(CAEDRErrorHandleCallback errorHandleCallback);
+
+
+/**
* @brief Get the local bluetooth adapter information.
*
* @param info [OUT] Local bluetooth adapter information
* fragmentation and reassemebly.
*/
-#ifndef CA_MSG_PARSER_H_
-#define CA_MSG_PARSER_H_
+#ifndef CA_FRAGMENTATION_H_
+#define CA_FRAGMENTATION_H_
#include "cacommon.h"
#include "logger.h"
/*****************************************************************
* @file The CA Header format
- * @brief CA Header will be difined by 2 bytes of Header.
+ * @brief CA Header will be defined 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.
+* @brief This function is used to generate the CA specific header to
+* maintain the fragmentation logic. The header structure
+* 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.
+* @param[in,out] header Pointer to the octet array that will contain
+* the generated header.
+* @param[in] length The total length of the data. The length will
+* be embedded in bits 5-16 of the header,
+* meaning the maximum overall length of the
+* data to be fragmented can be no more than 4096
+* (2^12).
*
-* @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
+* @return @c CA_STATUS_OK on success. One of the @c CA_STATUS_FAILED or
+* other error values on error.
+* @retval @c CA_STATUS_OK Successful
+* @retval @c CA_STATUS_INVALID_PARAM Invalid input arguments
+* @retval @c 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.
+* @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.
+* @param[in] header Pointer to the octet array data which contains the
+* header information. Note that pointer should
+* point to two bytes of data header which needs to
+* be parsed.
*
+* @return Overall length of the data to be reassembled, or 0 on
+* failure.
*/
uint32_t CAParseHeader(const char *header);
} /* extern "C" */
#endif
-#endif /* CA_MSG_PARSER_H_ */
+#endif /* CA_FRAGMENTATION_H_ */
#define CA_INTERFACE_CONTROLLER_H_
#include "caadapterinterface.h"
+
+#ifndef SINGLE_THREAD
#include "cathreadpool.h" /* for thread pool */
+#endif
#ifdef __cplusplus
extern "C"
{
#endif
+#ifdef SINGLE_THREAD
+/**
+ * @brief Initializes different adapters based on the compilation flags.
+ * @return none
+ */
+void CAInitializeAdapters();
+#else
/**
* @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);
+#endif
/**
* @brief Set the received packets callback for message handler
*/
void CATerminateAdapters();
+#ifdef SINGLE_THREAD
+/**
+ * @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();
+#endif
+
#ifdef __cplusplus
} /* extern "C" */
#endif
* started at Connectivity Abstraction Layer.
* @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
+ * @param errorCallback [IN] Callback to notify the network errors 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);
-
+CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
+ CANetworkPacketReceivedCallback networkPacketCallback,
+ CANetworkChangeCallback netCallback,
+ CAErrorHandleCallback errorCallback, ca_thread_pool_t handle);
/**
* @brief Start IP Interface adapter.
/**
* @brief Start discovery servers for receiving multicast advertisements
* Transport Specific Behavior:
- * IP Starts Start multicast server on a particular interface and prefixed port
+ * IP Starts multicast server on a particular interface and prefixed port
* number as per OIC Specification
* @return #CA_STATUS_OK or Appropriate error code
*/
/**
* @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 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.
+ * @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 CAEndpoint_t *endpoint, const void *data,
- uint32_t dataLen);
+ uint32_t dataLen);
/**
- * @brief Sends Multicast data to the endpoint using the IP connectivity.
+ * @brief Send Multicast data to the endpoint using the IP connectivity.
* @param endpoint [IN] Remote Endpoint information (like ipaddress , port)
- * @param data [IN] Data which required 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.
+ * @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 CAEndpoint_t *endpoint, const void *data, uint32_t dataLen);
+++ /dev/null
-/******************************************************************
- *
- * 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 CAEndpoint_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 CAEndpoint_t *endpoint, 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(CAEndpoint_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_ */
-
*/
typedef enum
{
- CA_UNICAST_SERVER = 0, /**< Unicast Server */
- CA_MULTICAST_SERVER, /**< Multicast Server */
- CA_SECURED_UNICAST_SERVER /**< Secured Unicast Server */
+ CA_UNICAST_SERVER = 0, /**< Unicast Server */
+ CA_MULTICAST_SERVER, /**< Multicast Server */
+ CA_SECURED_UNICAST_SERVER /**< Secured Unicast Server */
} CAAdapterServerType_t;
/**
uint32_t dataLength);
/**
+ * @brief Callback to notify error in the IP adapter
+ *
+ * @param endpoint [IN] [IN] network endpoint description
+ * @param data [IN] Data sent/received
+ * @param dataLength [IN] Length of data in bytes.
+ * @param result [IN] result of request from R.I
+ * @return NONE
+ * @pre Callback must be registered using CAIPSetPacketReceiveCallback()
+ */
+typedef void (*CAIPErrorHandleCallback)(const CAEndpoint_t *endpoint, const void *data,
+ uint32_t dataLength, CAResult_t result);
+
+/**
* @brief Callback to be notified when exception occures on multicast/unicast server.
* @param type [IN] Type of server(#CAAdapterServerType_t)
* @return NONE
* @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_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);
+CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, bool secured);
/**
* @brief Stop servers that are running in particular interface address.
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);
+
+/**
* @brief API to send unicast UDP data
*
* @param endpoint [IN] complete network address to send to
CAResult_t CAIPStopNetworkMonitor();
/**
+ * @brief Pull the Received Data
+ * @return NONE
+ */
+void CAIPPullData();
+
+/**
* @brief Get local adapter network information.
*
* @param netInterfaceList [OUT] network interface information list
*/
void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback);
+/**
+ * @brief Set callback for error handling
+ *
+ * @param ipErrorCallback [IN] callback to notify error to the ipadapter
+ * @return NONE
+ */
+void CAIPSetErrorHandleCallback(CAIPErrorHandleCallback ipErrorCallback);
+
#ifdef __cplusplus
}
#endif
+++ /dev/null
-/******************************************************************
-*
-* 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_ */
-
* started at Connectivity Abstraction Layer.
* @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
+ * @param errorCallback [IN] errorCallback to notify error to connectivity common logic
+ * layer from adapter
* @param handle [IN] Threadpool Handle
* @return #CA_STATUS_OK or Appropriate error code
*/
CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
CANetworkPacketReceivedCallback reqRespCallback,
CANetworkChangeCallback netCallback,
- ca_thread_pool_t handle);
+ CAErrorHandleCallback errorCallback, ca_thread_pool_t handle);
/**
* @brief Starting LE connectivity adapters.
* @retval #CA_STATUS_FAILED Operation failed
*
*/
-CAResult_t CABLEServerReceivedData(const char *remoteAddress, const char *serviceUUID,
- const void *data, uint32_t dataLength, uint32_t *sentLength);
+CAResult_t CALEAdapterServerReceivedData(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
* @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);
+CAResult_t CALEAdapterClientReceivedData(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
* @param callback [IN] callback handle sent from the upper layer.
* @return NONE
*/
-void CASetBLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
+void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
/**
* @brief This function will push the data from CA layer to the Sender processor queue.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABLEServerSendData(const CAEndpoint_t *remoteEndpoint,
- const void *data, uint32_t dataLen);
+CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
+ const void *data, uint32_t dataLen);
/**
* @brief This function will push the data from CA layer to the Sender processor queue.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABLEClientSendData(const CAEndpoint_t *remoteEndpoint,
- const void *data, uint32_t dataLen);
+CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
+ const void *data, uint32_t dataLen);
/**
* @brief This function will be associated with the sender queue for GattServer.This function will
*
* @return NONE
*/
-void CABLEServerSendDataThread(void *threadData);
+void CALEServerSendDataThread(void *threadData);
/**
* @brief This function will be associated with the sender queue for GattClient.This function will
*
* @return NONE
*/
-void CABLEClientSendDataThread(void *threadData);
+void CALEClientSendDataThread(void *threadData);
/**
* @brief This function will be associated with the receiver queue of GattServer. This function
*
* @return NONE
*/
-void CABLEServerDataReceiverHandler(void *threadData);
+void CALEServerDataReceiverHandler(void *threadData);
/**
* @brief This function will be associated with the receiver queue of GattClient. This function
* and Data.
* @return NONE
*/
-void CABLEClientDataReceiverHandler(void *threadData);
+void CALEClientDataReceiverHandler(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();
+void CAInitLEQueues();
/**
* @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();
+void CAStopLEQueues();
/**
* @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();
+void CATerminateLEQueues();
/**
* @brief This function will initalize the Receiver and Sender queues for GattServer. This
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitBleServerQueues();
+CAResult_t CAInitLEServerQueues();
/**
* @brief This function will initalize the Receiver and Sender queues for GattClient. This
* @retval #CA_STATUS_FAILED Operation failed
*
*/
-CAResult_t CAInitBleClientQueues();
+CAResult_t CAInitLEClientQueues();
/**
* @brief This function will initalize the Receiver queue for GattServer. This will initialize
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitBleServerSenderQueue();
+CAResult_t CAInitLEServerSenderQueue();
/**
* @brief This function will initalize the Receiver queue for GattClient. This will initialize
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitBleClientSenderQueue();
+CAResult_t CAInitLEClientSenderQueue();
/**
* @brief This function will initalize the Receiver queue for GattServer. This will initialize
* @retval #CA_STATUS_FAILED Operation failed
*
*/
-CAResult_t CAInitBleServerReceiverQueue();
+CAResult_t CAInitLEServerReceiverQueue();
/**
* @brief This function will initalize the Receiver queue for GattClient. This will initialize
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitBleClientReceiverQueue();
+CAResult_t CAInitLEClientReceiverQueue();
/**
* @brief This function will create the Data required to send it in the queue.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CALEData_t *CACreateBLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
+CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
* @param bleData [IN] Structure contains the information of a particular data segment.
* @return NONE
*/
-void CAFreeBLEData(CALEData_t *bleData);
+void CAFreeLEData(CALEData_t *bleData);
/**
* @brief This will be used to notify device status changes to the LE adapter layer
+++ /dev/null
-/* ****************************************************************
- *
- * 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
-{
- CAEndpoint_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 CAEndpoint_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 CAEndpoint_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(CAEndpoint_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 CAEndpoint_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 CAEndpoint_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 CAEndpoint_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_ */
-
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAStartBleGattServer();
+CAResult_t CAStartLEGattServer();
/**
* @brief Used to stop BLE Gatt Service.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAStopBleGattServer();
+CAResult_t CAStopLEGattServer();
/**
* @brief Used to stop Gatt Server thread and remove service registration, stop advertising.
* @return NONE
*/
-void CATerminateBleGattServer();
+void CATerminateLEGattServer();
/**
* @brief Used to store upper layer callback locally which will be used to send the data to
* @param callback [IN] Callback function to pass the data to CA layer.
* @return NONE
*/
-void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback);
+void CASetLEReqRespServerCallback(CABLEServerDataReceivedCallback callback);
/**
* @brief Used to update characteristics(Read/Write) value that we want to send to particular
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
- const uint32_t charValueLen);
+ uint32_t charValueLen);
/**
* @brief Used to start CAStartBleGattClientThread for initializing Gatt Client
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAStartBLEGattClient();
+CAResult_t CAStartLEGattClient();
/**
* @brief Used to stop Gatt Client gracefully in turn it will call CATerminateBLEGattClient
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-void CAStopBLEGattClient();
+void CAStopLEGattClient();
/**
* @brief Used to unset all the callbacks and stop service discovery
* @return NONE
*/
-void CATerminateBLEGattClient();
+void CATerminateLEGattClient();
+
+/**
+ * @brief API to read the data from characteristics and invoke notifyCallback.
+ * @return - NONE
+ */
+void CACheckLEData();
/**
* @brief Sets the value of characteristic and update the value to GATTServer(unicast).
*
* @return void
*/
-void CASetBLEReqRespClientCallback(CABLEClientDataReceivedCallback callback);
+void CASetLEReqRespClientCallback(CABLEClientDataReceivedCallback callback);
/**
* @brief Used to Set the gThreadPool handle which is required for spawning new thread.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-void CASetBleServerThreadPoolHandle(ca_thread_pool_t handle);
+void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle);
/**
* @brief Used to Set the gThreadPool handle which is required for spawning new thread.
* task.
* @return NONE
*/
-void CASetBleClientThreadPoolHandle(ca_thread_pool_t handle);
+void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle);
/**
* @brief Used to unset the callback of adapter connection state change.
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAUnSetLEAdapterStateChangedCb();
+
+/**
+ * @brief This will be used to notify errors in BLE adapter
+ * @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 result [IN] error code as per CAResult_t
+ * @return NONE
+ */
+typedef void (*CABLEErrorHandleCallback)(const char *remoteAddress, const void *data,
+ uint32_t dataLength, CAResult_t result);
+/**
+ * @brief sets the error handle callback
+ * @param callback [IN] Callback function to update error to the adapter
+ * @return NONE
+ */
+void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback);
+
+
+/**
+ * @brief sets the error handle callback
+ * @param callback [IN] Callback function to update error to the adapter
+ * @return NONE
+ */
+void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback);
+
#ifdef __cplusplus
}
#endif
+++ /dev/null
-/* ****************************************************************
-*
-* 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_ */
-
#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))))
+
+// 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
+
/**
* @brief generates pdu structure from the given information.
* @param code [IN] code of the pdu packet
* @return generated pdu
*/
coap_pdu_t *CAGeneratePDUImpl(code_t code, coap_list_t *options, const CAInfo_t *info,
- const char *payload, size_t payloadSize);
+ const uint8_t *payload, size_t payloadSize);
/**
* @brief parse the URI and creates the options
#define DEFAULT_ACK_TIMEOUT_SEC 2
/** default max retransmission trying count is 4.(CoAP) **/
-#define DEFAULT_MAX_RETRANSMIT 4
+#define DEFAULT_RETRANSMISSION_COUNT 4
/** check period is 1 sec. **/
#define RETRANSMISSION_CHECK_PERIOD_SEC 1
* 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,
+CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
+ ca_thread_pool_t handle,
CADataSendMethod_t retransmissionSendMethod,
CATimeoutCallback_t timeoutCallback,
CARetransmissionConfig_t* config);
*/
CAResult_t CARetransmissionDestroy(CARetransmission_t *context);
+/**
+ * @brief Invoke Retransmission according to TimedAction Response
+ * @param threadValue [IN] context for retransmission
+ */
+void CARetransmissionBaseRoutine(void *threadValue);
+
#ifdef __cplusplus
} /* extern "C" */
#endif
+++ /dev/null
-/******************************************************************
- *
- * 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_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
-
-/** 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 CAEndpoint_t *endpoint, const void *pdu,
- uint32_t size);
-
-/** retransmission timeout callback type**/
-typedef void (*CATimeoutCallback_t)(const CAEndpoint_t *endpoint, const void *pdu,
- uint32_t size);
-
-typedef struct
-{
- /** retransmission support transport type **/
- CATransportAdapter_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 CAEndpoint_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 CAEndpoint_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_ */
-
libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_')
libcoap_env.InstallTarget([libcoap], 'libcoap')
+libcoap_env.UserInstallTargetLib([libcoap], 'libcoap')
return 1;
}
-int coap_get_data(coap_pdu_t *pdu, size_t *len, unsigned char **data)
+int coap_get_data(const coap_pdu_t *pdu, size_t *len, unsigned char **data)
{
assert(pdu);
assert(len);
* 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);
+int coap_get_data(const coap_pdu_t *pdu, size_t *len, unsigned char **data);
#endif /* _PDU_H_ */
\r
libRMInterface = app_env.SharedLibrary('RMInterface', sample_src, OBJPREFIX='libRMInterface_')\r
app_env.InstallTarget(libRMInterface, 'RMInterface')\r
+app_env.UserInstallTargetLib(libRMInterface, 'RMInterface')\r
\r
\r
#define OPTION_INFO_LENGTH 1024
#define NETWORK_INFO_LENGTH 1024
-uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
+typedef struct
+{
+ char ipAddress[CA_IPADDR_SIZE];
+ uint16_t port;
+} addressSet_t;
void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo);
void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo);
CAResult_t get_network_type(uint32_t selectedNetwork);
void callback(char *subject, char *receivedData);
CAResult_t get_remote_address(CATransportAdapter_t transportType, const char *address);
+void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
+uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
CATransportAdapter_t g_selectedNwType = CA_ADAPTER_IP;
static CAToken_t g_lastRequestToken = NULL;
-static uint8_t g_lastRequestTokenLength;
+static uint8_t g_lastRequestTokenLength = 0;
-static const char SECURE_COAPS_PREFIX[] = "coaps://";
+static const char COAP_PREFIX[] = "coap://";
+static const char COAPS_PREFIX[] = "coaps://";
+static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
+static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
static const char SECURE_INFO_DATA[]
= "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
- "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+ "\"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 JavaVM *g_jvm;
static CAEndpoint_t *g_clientEndpoint = NULL;
-static char *g_resourceUri;
-static CAToken_t g_clientToken;
-static uint8_t g_clientTokenLength = NULL;
+static char *g_resourceUri = NULL;
+static CAToken_t g_clientToken = NULL;
+static uint8_t g_clientTokenLength = 0;
-static uint16_t g_clientMsgId;
+static uint16_t g_clientMsgId = 0;
static char *g_remoteAddress = NULL;
// init
JNIEXPORT void JNICALL
Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
- jobject listener)
+ jobject listener)
{
LOGI("setNativeResponseListener");
g_responseListenerObject = (*env)->NewGlobalRef(env, obj);
}
JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMFindResource(JNIEnv *env, jobject obj, jstring uri)
-{
- LOGE("Java_org_iotivity_service_RMInterface_RMFindResource not implemented");
-}
-
-JNIEXPORT void JNICALL
Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
- jstring payload, jint selectedNetwork,
- jint isSecured, jint msgType)
+ jstring payload, jint selectedNetwork,
+ jint isSecured, jint msgType)
{
LOGI("selectedNetwork - %d", selectedNetwork);
CAResult_t res = get_network_type(selectedNetwork);
const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
LOGI("RMSendRequest - %s", strUri);
+ CATransportFlags_t flags;
+ addressSet_t address = {};
+ parsing_coap_uri(strUri, &address, &flags);
+
//create remote endpoint
CAEndpoint_t* endpoint = NULL;
- res = CACreateEndpoint(CA_DEFAULT_FLAGS, g_selectedNwType, strUri, 0, &endpoint);
- //ReleaseStringUTFChars for strUri
- (*env)->ReleaseStringUTFChars(env, uri, strUri);
-
+ res = CACreateEndpoint(flags, g_selectedNwType, (const char*)address.ipAddress,
+ address.port, &endpoint);
if (CA_STATUS_OK != res)
{
LOGE("Could not create remote end point");
+ (*env)->ReleaseStringUTFChars(env, uri, strUri);
return;
}
LOGE("token generate error!!");
// destroy remote endpoint
CADestroyEndpoint(endpoint);
+ (*env)->ReleaseStringUTFChars(env, uri, strUri);
return;
}
char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
+ (*env)->ReleaseStringUTFChars(env, uri, strUri);
CAInfo_t requestData = { 0 };
requestData.token = token;
}
requestData.type = messageType;
+ requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
+ if (NULL == requestData.resourceUri)
+ {
+ LOGE("Memory allocation failed!");
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyEndpoint(endpoint);
+ free(requestData.payload);
+ return;
+ }
+ memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
CADestroyEndpoint(endpoint);
free(requestData.payload);
+ free(requestData.resourceUri);
}
JNIEXPORT void JNICALL
Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
- jint selectedNetwork)
+ jint selectedNetwork)
{
LOGI("selectedNetwork - %d", selectedNetwork);
CAResult_t res = get_network_type(selectedNetwork);
return;
}
- const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
- LOGI("RMSendReqestToAll - %s", strUri);
-
// create remote endpoint
CAEndpoint_t *endpoint = NULL;
- res = CACreateEndpoint(CA_DEFAULT_FLAGS, g_selectedNwType, strUri, 0, &endpoint);
-
- //ReleaseStringUTFChars for strUri
- (*env)->ReleaseStringUTFChars(env, uri, strUri);
+ res = CACreateEndpoint(CA_DEFAULT_FLAGS, g_selectedNwType, NULL, 0, &endpoint);
if (CA_STATUS_OK != res)
{
requestData.payload = "Temp Json Payload";
requestData.type = CA_MSG_NONCONFIRM;
+ const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
+ LOGI("resourceUri - %s", strUri);
+ requestData.resourceUri = (CAURI_t)strUri;
+
+ uint8_t optionNum = 2;
+ CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
+ sizeof(CAHeaderOption_t) * optionNum);
+ if (NULL == headerOpt)
+ {
+ LOGE("Memory allocation failed");
+ return;
+ }
+
+ char* FirstOptionData = "Hello";
+ headerOpt[0].optionID = 3000;
+ memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
+ headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
+
+ char* SecondOptionData2 = "World";
+ headerOpt[1].optionID = 3001;
+ memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
+ headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
+
+ requestData.numOptions = optionNum;
+ requestData.options = headerOpt;
+
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
requestInfo.isMulticast = true;
g_lastRequestTokenLength = tokenLength;
}
+ //ReleaseStringUTFChars for strUri
+ (*env)->ReleaseStringUTFChars(env, uri, strUri);
+
+ free(headerOpt);
+
// destroy remote endpoint
CADestroyEndpoint(endpoint);
}
JNIEXPORT void JNICALL
Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
- jint selectedNetwork,
- jint isSecured, jint msgType,
- jint responseValue)
+ jint selectedNetwork,
+ jint isSecured, jint msgType,
+ jint responseValue)
{
LOGI("RMSendResponse");
CAInfo_t responseData = { 0 };
responseData.type = messageType;
responseData.messageId = g_clientMsgId;
+ responseData.resourceUri = (CAURI_t)g_resourceUri;
CAResponseInfo_t responseInfo = { 0 };
JNIEXPORT void JNICALL
Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
- jstring payload, jint selectedNetwork,
- jint isSecured, jint msgType,
- jint responseValue)
+ jstring payload, jint selectedNetwork,
+ jint isSecured, jint msgType,
+ jint responseValue)
{
LOGI("selectedNetwork - %d", selectedNetwork);
const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
LOGI("RMSendNotification - %s", strUri);
+ CATransportFlags_t flags;
+ addressSet_t address = {};
+ parsing_coap_uri(strUri, &address, &flags);
+
//create remote endpoint
CAEndpoint_t* endpoint = NULL;
- if (CA_STATUS_OK != CACreateEndpoint(CA_DEFAULT_FLAGS, g_selectedNwType, strUri, 0, &endpoint))
+ if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
+ (const char*)address.ipAddress,
+ address.port, &endpoint))
{
//ReleaseStringUTFChars for strUri
(*env)->ReleaseStringUTFChars(env, uri, strUri);
CAInfo_t responseData = { 0 };
responseData.token = token;
responseData.tokenLength = tokenLength;
+ responseData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
+ if (NULL == responseData.resourceUri)
+ {
+ LOGE("Memory allocation failed!");
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyEndpoint(endpoint);
+ return;
+ }
+ memcpy(responseData.resourceUri, resourceURI, sizeof(resourceURI));
if (1 == isSecured)
{
CADestroyToken(token);
// destroy remote endpoint
CADestroyEndpoint(endpoint);
+
+ free(responseData.resourceUri);
return;
}
snprintf(responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
CADestroyToken(token);
// destroy remote endpoint
CADestroyEndpoint(endpoint);
+
+ free(responseData.resourceUri);
return;
}
snprintf(responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
CADestroyEndpoint(endpoint);
free(responseData.payload);
+ free(responseData.resourceUri);
}
JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj, jint networkType)
+Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
+ jint networkType)
{
LOGI("RMSelectNetwork Type : %d", networkType);
}
JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj, jint networkType)
+Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
+ jint networkType)
{
LOGI("RMUnSelectNetwork Type : %d", networkType);
char *uri = NULL;
uint32_t length = 0;
- length = sizeof(SECURE_COAPS_PREFIX) - 1; //length of "coaps://"
+ length = COAPS_PREFIX_LEN; //length of "coaps://"
// length of "ipaddress:port"
length += strlen(object->addr) + PORT_LENGTH;
length += strlen(requestInfo->info.resourceUri) + 1;
free(uri);
return;
}
- sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addr,
+ sprintf(uri, "%s%s:%d/%s", COAPS_PREFIX, object->addr,
securePort, requestInfo->info.resourceUri);
CAEndpoint_t *endpoint = NULL;
if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
- object->adapter, uri, securePort, &endpoint))
+ object->adapter, object->addr, securePort, &endpoint))
{
LOGE("Failed to create duplicate of remote endpoint!");
free(uri);
return CA_STATUS_OK;
}
+
+
+void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
+{
+ if (NULL == uri || NULL == address)
+ {
+ LOGE("parameter is null");
+ return;
+ }
+
+ // parse uri
+ // #1. check prefix
+ uint8_t startIndex = 0;
+ if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
+ {
+ LOGI("uri has '%s' prefix", COAPS_PREFIX);
+ startIndex = COAPS_PREFIX_LEN;
+ *flags = CA_SECURE;
+ }
+ else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
+ {
+ LOGI("uri has '%s' prefix", COAP_PREFIX);
+ startIndex = COAP_PREFIX_LEN;
+ *flags = CA_DEFAULT_FLAGS;
+ }
+
+ // #2. copy uri for parse
+ int32_t len = strlen(uri) - startIndex;
+
+ if (len <= 0)
+ {
+ LOGE("uri length is 0!");
+ return;
+ }
+
+ char *cloneUri = (char *) calloc(len + 1, sizeof(char));
+ if (NULL == cloneUri)
+ {
+ LOGE("Out of memory");
+ return;
+ }
+
+ memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
+ cloneUri[len] = '\0';
+
+ char *pAddress = cloneUri;
+ char *pResourceUri = NULL;
+
+ int32_t i = 0;
+ for (i = 0; i < len; i++)
+ {
+ if (cloneUri[i] == '/')
+ {
+ // separate
+ cloneUri[i] = 0;
+ pResourceUri = &cloneUri[i + 1];
+ break;
+ }
+ }
+ LOGI("pAddress : %s", pAddress);
+
+ int res = get_address_set(pAddress, address);
+ if (res == -1)
+ {
+ LOGE("address parse error");
+
+ free(cloneUri);
+ return;
+ }
+ return;
+}
+
+int get_address_set(const char *pAddress, addressSet_t* outAddress)
+{
+ if (NULL == pAddress || NULL == outAddress)
+ {
+ LOGE("parameter is null");
+ return -1;
+ }
+
+ int32_t len = strlen(pAddress);
+ int32_t isIp = 0;
+ int32_t ipLen = 0;
+
+ int32_t i = 0;
+ for (i = 0; i < len; i++)
+ {
+ if (pAddress[i] == '.')
+ {
+ isIp = 1;
+ }
+
+ // found port number start index
+ if (isIp && pAddress[i] == ':')
+ {
+ ipLen = i;
+ break;
+ }
+ }
+
+ if (isIp)
+ {
+ if(ipLen && ipLen < sizeof(outAddress->ipAddress))
+ {
+ strncpy(outAddress->ipAddress, pAddress, ipLen);
+ outAddress->ipAddress[ipLen] = '\0';
+ }
+ else if (!ipLen && len < sizeof(outAddress->ipAddress))
+ {
+ strncpy(outAddress->ipAddress, pAddress, len);
+ outAddress->ipAddress[len] = '\0';
+ }
+ else
+ {
+ LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
+ return -1;
+ }
+
+ if (ipLen > 0)
+ {
+ outAddress->port = atoi(pAddress + ipLen + 1);
+ }
+ }
+ else
+ {
+ strncpy(outAddress->ipAddress, pAddress, len);
+ outAddress->ipAddress[len] = '\0';
+ }
+
+ return isIp;
+}
/*
* Class: org_iotivity_ca_service_RMInterface
- * Method: RMFindResource
- * Signature: (Ljava/lang/String;)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMFindResource
- (JNIEnv *, jobject, jstring);
-
-/*
- * Class: org_iotivity_ca_service_RMInterface
* Method: RMSendRequest
* Signature: (Ljava/lang/String;Ljava/lang/String;III)V
*/
/*
* Class: org_iotivity_ca_service_RMInterface
- * Method: RMAdvertiseResource
- * Signature: (Ljava/lang/String)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMAdvertiseResource
- (JNIEnv *, jobject, jstring);
-
-/*
- * Class: org_iotivity_ca_service_RMInterface
* Method: RMSendNotification
* Signature: (Ljava/lang/String;Ljava/lang/String;IIII)V
*/
</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"
</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" >
+ android:layout_below="@id/layout_Response_Noti_title" >
<EditText
android:id="@+id/et_notification"
</RelativeLayout>
<RelativeLayout
- android:id="@+id/layout_payload_server_ed"
+ android:id="@+id/layout_request_setting_for_server"
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"
+ <Button
+ android:id="@+id/btn_Request_setting_for_server"
+ android:layout_width="wrap_content"
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" >
+ android:layout_alignParentLeft="true"
+ android:text="@string/request_setting" />
<Button
android:id="@+id/btn_notify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
+ android:layout_toRightOf="@id/btn_Request_setting_for_server"
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" />
+ android:layout_toRightOf="@id/btn_notify"
+ android:text="@string/sendresponse" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/layout_request_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
- android:layout_below="@id/layout_find" >
+ android:layout_below="@id/layout_mode" >
<TextView
android:id="@+id/tv_request"
android:layout_height="wrap_content"
android:text="[Send Request]" />
- </RelativeLayout>
+ </RelativeLayout>
<RelativeLayout
android:id="@+id/layout_request"
</RelativeLayout>
<RelativeLayout
- android:id="@+id/layout_payload_client_ed"
+ android:id="@+id/layout_request_setting_for_client"
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"
+ <Button
+ android:id="@+id/btn_Request_setting_for_client"
+ android:layout_width="wrap_content"
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" >
+ android:layout_alignParentLeft="true"
+ android:text="@string/request_setting" />
<Button
android:id="@+id/btn_Request"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
+ android:layout_toRightOf="@id/btn_Request_setting_for_client"
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:layout_below="@id/layout_request_to_all" >
<Button
- android:id="@+id/btn_request_to_all"
+ android:id="@+id/btn_request_to_all_setting_for_client"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:text="@string/request_to_all" />
+ android:layout_alignParentLeft="true"
+ android:text="@string/request_setting" />
<Button
- android:id="@+id/btn_request_to_all_setting_for_client"
- android:layout_width="fill_parent"
+ android:id="@+id/btn_request_to_all"
+ android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_toLeftOf="@id/btn_request_to_all"
- android:text="@string/request_setting" />
+ android:layout_toRightOf="@id/btn_request_to_all_setting_for_client"
+ android:text="@string/request_to_all" />
</RelativeLayout>
<RelativeLayout
android:layout_below="@id/layout_handle_title" >
<Button
- android:id="@+id/btn_get_network_info"
+ android:id="@+id/btn_receive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:text="@string/get_network_info" />
+ android:layout_alignParentLeft="true"
+ android:text="@string/receive" />
+
<Button
- android:id="@+id/btn_receive"
- android:layout_width="fill_parent"
+ android:id="@+id/btn_get_network_info"
+ android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_toLeftOf="@id/btn_get_network_info"
- android:text="@string/receive" />
+ android:layout_toRightOf="@id/btn_receive"
+ android:text="@string/get_network_info" />
+
</RelativeLayout>
</RelativeLayout>
android:layout_height="wrap_content" />
</ScrollView>
-</RelativeLayout>
+</RelativeLayout>
\ No newline at end of file
<?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="sendresponse">Response</string>
+ <string name="notify">Notification</string>
+ <string name="request_setting">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="coap_prefix">coap://</string>
+ <string name="port_num">:6298</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="remote_address">"Remote Address: "</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
public class CaLeClientInterface {
- private static String SERVICE_UUID = "713d0000-503e-4c75-ba94-3148f18d941e";
+ private static String SERVICE_UUID = "ADE3D529-C784-4F63-A987-EB69F70EE816";
+ private static String TAG = "Sample_Service : CaLeClientInterface";
private CaLeClientInterface(Context context) {
try {
List<UUID> uuids = getUuids(scanRecord);
for (UUID uuid : uuids) {
- Log.d("CA", "UUID : " + uuid.toString());
- if(uuid.toString().contains(SERVICE_UUID)) {
- Log.d("CA", "we found that has the Device");
+ Log.d(TAG, "UUID : " + uuid.toString());
+ if(uuid.toString().contains(SERVICE_UUID.toLowerCase())) {
+ Log.d(TAG, "we found that has the Device");
caLeScanCallback(device, rssi, scanRecord);
}
}
long leastSigBits = buffer.getLong();
uuids.add(new UUID(leastSigBits, mostSigBits));
} catch (IndexOutOfBoundsException e) {
- Log.e("CA", e.toString());
+ Log.e(TAG, e.toString());
continue;
} finally {
offset += 15;
public final class DLog {
- private final static String MAIN_TAG = "Sample_Service";
+ private final static String MAIN_TAG = "Sample_Service : DLog";
private static TextView mLogView = null;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
+import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
static RMInterface RM = new RMInterface();
- private final static String TAG = "MainActivity";
+ private final static String TAG = "Sample_Service : MainActivity";
- private final CharSequence[] mNetworkCheckBoxItems = { Network.IPV4.name(),
- Network.IPV6.name(), Network.EDR.name(), Network.LE.name()};
+ private final CharSequence[] mNetworkCheckBoxItems = { Network.IP.name(),
+ Network.LE.name(), Network.EDR.name()};
private final CharSequence[] mDTLSCheckBoxItems = { DTLS.UNSECURED.name(),
DTLS.SECURED.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_DELETED.name(), ResponseResult.CA_VALID.name(),
+ ResponseResult.CA_CHANGED.name(), ResponseResult.CA_CONTENT.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 Network {
- IPV4, IPV6, EDR, LE
+ IP, LE, EDR
};
private enum DTLS {
};
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
+ CA_SUCCESS, CA_CREATED, CA_DELETED, CA_VALID, CA_CHANGED, CA_CONTENT, 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 mSelectedItems[] = { 0, 0, 0 };
- private int mUnSelectedItems[] = { 0, 0, 0, 0 };
+ private int mUnSelectedItems[] = { 0, 0, 0 };
private Mode mCurrentMode = Mode.UNKNOWN;
- private RelativeLayout mFindResourceLayout = null;
-
private RelativeLayout mSendNotificationLayout = null;
private RelativeLayout mSendRequestLayout = 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;
/**
* Defined ConnectivityType in cacommon.c
*
- * CA_IPV4 = (1 << 0) CA_IPV6 = (1 << 1) CA_EDR = (1 << 2) CA_LE = (1 << 3)
+ * CA_IP = (1 << 0) CA_LE = (1 << 2) CA_EDR = (1 << 3)
*/
- private int CA_IPV4 = (1 << 0);
- private int CA_IPV6 = (1 << 1);
+ private int CA_IP = (1 << 0);
+ private int CA_LE = (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;
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);
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);
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)");
+ Log.i(TAG, "Select Mode (Server or Client)");
}
private void showNetworkView() {
mNetwork_tv.setText("Select Network Type");
+ Log.i(TAG, "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);
+ mSendRequestToAllLayout.setVisibility(View.VISIBLE);
mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
- mSendRequestToAllSettingLayout.setVisibility(View.INVISIBLE);
+ mSendRequestToAllSettingLayout.setVisibility(View.VISIBLE);
mReceiveLayout.setVisibility(View.VISIBLE);
- mFindTitleLayout.setVisibility(View.INVISIBLE);
mRequestTitleLayout.setVisibility(View.INVISIBLE);
- mRequestToAllTitleLayout.setVisibility(View.INVISIBLE);
+ mRequestToAllTitleLayout.setVisibility(View.VISIBLE);
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);
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("");
if (interestedNetwork == 0) {
mCurrentMode = Mode.SERVER;
mMode_tv.setText("MODE: " + mCurrentMode.toString());
+ Log.i(TAG, "MODE: " + mCurrentMode.toString());
showNetworkView();
} else {
mCurrentMode = Mode.SERVER;
mMode_tv.setText("MODE: " + mCurrentMode.toString());
+ Log.i(TAG, "MODE: " + mCurrentMode.toString());
showModeView();
}
if (interestedNetwork == 0) {
mCurrentMode = Mode.CLIENT;
mMode_tv.setText("MODE: " + mCurrentMode.toString());
+ Log.i(TAG, "MODE: " + mCurrentMode.toString());
showNetworkView();
} else {
mCurrentMode = Mode.CLIENT;
mMode_tv.setText("MODE: " + mCurrentMode.toString());
+ Log.i(TAG, "MODE: " + mCurrentMode.toString());
showModeView();
}
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
DLog.v(TAG, "SendNotification click");
if ( selectedNetwork != -1) {
RM.RMSendNotification(mNotification_ed.getText().toString(),
- mPayload_ed.getText().toString(), selectedNetwork,
- isSecured, msgType, responseValue);
+ null, 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
DLog.v(TAG, "SendRequest click");
if ( selectedNetwork != -1) {
- RM.RMSendRequest(mReqData_ed.getText().toString(), mPayload_ed
- .getText().toString(), selectedNetwork, isSecured, msgType);
+ RM.RMSendRequest(mReqData_ed.getText().toString(), null,
+ selectedNetwork, isSecured, msgType);
}
else {
DLog.v(TAG, "Please Select Network Type");
for (int i = 0; i < mSelectedItems.length; i++) {
if (mSelectedItems[i] == 1) {
- if(i != 1)
- interestedNetwork |= (1 << i);
- else
- checkNotSupportedTransport("Not Supported Transport");
+ interestedNetwork |= (1 << i);
}
}
if(0 != interestedNetwork)
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;
+ uninterestedNetwork |= (1 << i);
}
}
if(0 != 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);
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");
}
.ordinal()) {
responseValue = 202;
DLog.v(TAG, "Response Value is CA_DELETED");
+ } else if (selectedResponseValue == ResponseResult.CA_VALID
+ .ordinal()) {
+ responseValue = 203;
+ DLog.v(TAG, "Response Value is CA_VALID");
+ } else if (selectedResponseValue == ResponseResult.CA_CHANGED
+ .ordinal()) {
+ responseValue = 204;
+ DLog.v(TAG, "Response Value is CA_CHANGED");
+ } else if (selectedResponseValue == ResponseResult.CA_CONTENT
+ .ordinal()) {
+ responseValue = 205;
+ DLog.v(TAG, "Response Value is CA_CONTENT");
} else if (selectedResponseValue == ResponseResult.CA_EMPTY
.ordinal()) {
responseValue = 0;
@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");
+ if (selectedNetworkType == Network.IP.ordinal()) {
+ selectedNetwork = CA_IP;
+ DLog.v(TAG, "Selected Network is CA_IP");
} else if (selectedNetworkType == Network.LE.ordinal()) {
selectedNetwork = CA_LE;
DLog.v(TAG, "Selected Network is LE");
- }
- else {
+ } else if (selectedNetworkType == Network.EDR.ordinal()) {
+ selectedNetwork = CA_EDR;
+ DLog.v(TAG, "Selected Network is EDR");
+ } else {
DLog.v(TAG, "Selected Network is NULL");
selectedNetwork = -1;
}
String callbackData = subject + receivedData;
DLog.v(TAG, callbackData);
+ if (subject.equals(getString(R.string.remote_address))) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(getString(R.string.coap_prefix)).append(receivedData);
+ if (receivedData.contains(".")) { // IP
+ sb.append(getString(R.string.port_num));
+ }
+ sb.append(getString(R.string.uri));
+ mReqData_ed.setText(sb.toString());
+ mNotification_ed.setText(sb.toString());
+ }
}
}
#define MAX_BUF_LEN 100 //1024
#define MAX_OPT_LEN 16
+#define PORT_LENGTH 5
static bool g_isLeSelected = false;
static void SelectNetwork();
static void UnselectNetwork();
static void HandleRequestResponse();
+static void GetNetworkInfo();
static void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
static void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
readInput[len] = '\0';
Serial.flush();
- Serial.print("PD:");
+ Serial.print("PD: ");
Serial.println(readInput);
(*dataLength) = len;
}
-bool ParseData(char *buf, char *url, char *resourceUri)
+bool ParseData(char *buf, char *url, char *port, char *resourceUri)
{
char *slash = strchr(buf, '/');
if (!slash)
if (dot && dot < slash)
{
char *colon = strchr(buf, ':');
+
+ if (colon)
+ {
+ strncpy(port, colon, slash - colon);
+ memmove(port, port+1, strlen(port));
+ }
if (colon && colon < slash)
{
strncpy(url, buf, colon - buf);
char type[2] = {0};
Serial.println("Select network");
Serial.println("IP: 0");
- Serial.println("RFCOMM (EDR): 1");
- Serial.println("GATT (BLE): 2");
+ Serial.println("GATT (BLE): 1");
+ Serial.println("RFCOMM (EDR): 2");
size_t typeLen = 0;
GetData(type, sizeof(type), &typeLen);
case '0':
return CA_ADAPTER_IP;
case '1':
- return CA_ADAPTER_RFCOMM_BTEDR;
- case '2':
return CA_ADAPTER_GATT_BTLE;
+ case '2':
+ return CA_ADAPTER_RFCOMM_BTEDR;
}
return CA_ADAPTER_IP;
}
StartDiscoveryServer();
break;
- case 'F': // find resource
- SendRequestAll();
- break;
-
case 'R': // send request
SendRequest();
break;
+
case 'E': //send request to all
SendRequestAll();
break;
case 'B': // send notification
SendNotification();
break;
+ case 'G': // Get network info
+ GetNetworkInfo();
+ break;
case 'N': // select network
SelectNetwork();
char buf[MAX_BUF_LEN] = {0};
char address[MAX_BUF_LEN] = {0};
char resourceUri[MAX_BUF_LEN] = {0};
+ char port[PORT_LENGTH] = {0};
CATransportAdapter_t selectedNetwork;
selectedNetwork = GetConnectivityType();
return;
}
- if (!ParseData(buf, address, resourceUri))
+ if (!ParseData(buf, address, port, resourceUri))
{
Serial.println("bad uri");
return;
// create remote endpoint
CAEndpoint_t *endpoint = NULL;
- CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
+ CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
+ &endpoint);
if (res != CA_STATUS_OK)
{
Serial.println("Out of memory");
requestInfo.method = CA_GET;
requestInfo.isMulticast = false;
requestInfo.info = requestData;
+ requestInfo.isMulticast = false;
// send request
CASendRequest(endpoint, &requestInfo);
char buf[MAX_BUF_LEN] = {0};
char address[MAX_BUF_LEN] = {0};
char resourceUri[MAX_BUF_LEN] = {0};
+ char port[PORT_LENGTH] = {0};
CATransportAdapter_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("/resource_uri (any adapter)");
- Serial.println("uri : ");
+ Serial.println("\n=============================================\n");
+ Serial.println("ex) /a/light\n");
+ Serial.println("resource uri : ");
size_t len = 0;
GetData(buf, sizeof(buf), &len);
return;
}
- if (!ParseData(buf, address, resourceUri))
+ if (!ParseData(buf, address, port, resourceUri))
{
Serial.println("bad uri");
return;
// create remote endpoint
CAEndpoint_t *endpoint = NULL;
- CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
+ CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
+ &endpoint);
if (res != CA_STATUS_OK)
{
CAInfo_t requestData = {CA_MSG_RESET};
requestData.token = token;
requestData.tokenLength = tokenLength;
- requestData.payload = "Temp Json Payload";
+ requestData.payload = (CAPayload_t)"Temp Json Payload";
requestData.type = CA_MSG_NONCONFIRM;
requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
strcpy(requestData.resourceUri, resourceUri);
requestInfo.info = requestData;
// send request
- // CASendRequest(endpoint, &requestInfo);
CASendRequest(endpoint, &requestInfo);
if (NULL != token)
char buf[MAX_BUF_LEN] = {0};
char address[MAX_BUF_LEN] = {0};
char resourceUri[MAX_BUF_LEN] = {0};
+ char port[PORT_LENGTH] = {0};
CATransportAdapter_t selectedNetwork;
selectedNetwork = GetConnectivityType();
return;
}
- if (!ParseData(buf, address, resourceUri))
+ if (!ParseData(buf, address, port, resourceUri))
{
Serial.println("bad uri");
return;
// create remote endpoint
CAEndpoint_t *endpoint = NULL;
- CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
+ CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port),
+ &endpoint);
if (CA_STATUS_OK != res)
{
Serial.println("Out of memory");
strcpy(respondData.resourceUri, resourceUri);
CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
- responseInfo.result = CA_SUCCESS;
+ responseInfo.result = CA_CONTENT;
responseInfo.info = respondData;
// send request
Serial.println("============");
Serial.println("Select network");
Serial.println("IP: 0");
- Serial.println("EDR: 1");
- Serial.println("LE: 2\n");
+ Serial.println("LE: 1");
+ Serial.println("EDR: 2\n");
size_t len = 0;
GetData(buf, sizeof(buf), &len);
#endif
}
break;
+ case 1:
+ g_isLeSelected = true;
+ break;
case 2:
// Nothing TBD here
break;
- case 3:
- g_isLeSelected = true;
- break;
}
CASelectNetwork(CATransportAdapter_t(1<<number));
Serial.println("============");
Serial.println("Unselect network");
Serial.println("IPv4: 0");
- Serial.println("EDR: 2");
- Serial.println("LE: 3\n");
+ Serial.println("LE: 1");
+ Serial.println("EDR: 2\n");
size_t len = 0;
GetData(buf, sizeof(buf), &len);
Serial.println("============");
}
+void GetNetworkInfo()
+{
+ CAEndpoint_t *tempInfo = NULL;
+ uint32_t tempSize = 0;
+ CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+ if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
+ {
+ Serial.println("Network not connected");
+ free(tempInfo);
+ return;
+ }
+ Serial.println("=========");
+ Serial.print("Network info total size is ");
+ Serial.println(tempSize);
+ int index;
+ for (index = 0; index < tempSize; index++)
+ {
+ Serial.print("Type: ");
+ Serial.println(tempInfo[index].adapter);
+ if (CA_ADAPTER_IP == tempInfo[index].adapter)
+ {
+ Serial.print("Address: ");
+ Serial.println(tempInfo[index].addr);
+ Serial.print("Port: ");
+ Serial.println(tempInfo[index].port);
+ }
+ }
+ free(tempInfo);
+ Serial.println("=======");
+}
+
void PrintMenu()
{
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("g: get network info");
Serial.println("n: select network");
Serial.println("x: unselect network");
Serial.println("h: handle request response");
return;
}
- Serial.println("RAddr: ");
+ Serial.print("RAddr: ");
Serial.println(object->addr);
- Serial.println("Port: ");
+ Serial.print("Port: ");
Serial.println(object->port);
- Serial.println("uri: ");
+ Serial.print("uri: ");
Serial.println(requestInfo->info.resourceUri);
- Serial.println("data: ");
- Serial.println(requestInfo->info.payload);
- Serial.println("Type: ");
+ Serial.print("data: ");
+ Serial.println((char*)requestInfo->info.payload);
+ Serial.print("Type: ");
Serial.println(requestInfo->info.type);
if (requestInfo->info.options)
uint32_t i;
for (i = 0; i < len; i++)
{
- Serial.println("Option:");
+ Serial.print("Option: ");
Serial.println(i+1);
- Serial.println("ID:");
+ Serial.print("ID: ");
Serial.println(requestInfo->info.options[i].optionID);
- Serial.println("Data:");
+ Serial.print("Data: ");
Serial.println((char*)requestInfo->info.options[i].optionData);
}
}
Serial.print("uri: ");
Serial.println(responseInfo->info.resourceUri);
Serial.print("data: ");
- Serial.println(responseInfo->info.payload);
+ Serial.println((char*)responseInfo->info.payload);
Serial.print("Type: ");
Serial.println(responseInfo->info.type);
Serial.print("res result=");
void ErrorHandler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
{
- printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
+ Serial.println("ErrorInfo");
if(errorInfo)
{
const CAInfo_t *info = &errorInfo->info;
- printf("Error Handler, ErrorInfo :\n");
- printf("Error Handler result : %d\n", errorInfo->result);
- printf("Error Handler token : %s\n", info->token);
- printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
- printf("Error Handler type : %d\n", info->type);
- printf("Error Handler resourceUri : %s\n", info->resourceUri);
- printf("Error Handler payload : %s\n", info->payload);
-
- if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
- {
- printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
- }
- else if(CA_SEND_FAILED == errorInfo->result)
- {
- printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
- }
- else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
- {
- printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
- }
- else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
- {
- printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
- }
- else if(CA_STATUS_FAILED == errorInfo->result)
- {
- printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
- }
+ Serial.print("result: ");
+ Serial.println(errorInfo->result);
+ Serial.print("token: ");
+ Serial.println(info->token);
+ Serial.print("messageId: ");
+ Serial.println(info->messageId);
+ Serial.print("type: ");
+ Serial.println(info->type);
+ Serial.print("resourceUri: ");
+ Serial.println(info->resourceUri);
+ Serial.print("payload: ");
+ Serial.println((char*)info->payload);
}
- printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
return;
}
Serial.println("Success: 200");
Serial.println("Created: 201");
Serial.println("Deleted: 202");
+ Serial.println("Valid : 203");
+ Serial.println("Changed: 204");
+ Serial.println("Content: 205");
Serial.println("BadReq : 400");
Serial.println("BadOpt : 402");
Serial.println("NotFnd : 404");
CAInfo_t responseData = {CA_MSG_RESET};
responseData.type = static_cast<CAMessageType_t>(messageType);
responseData.messageId = (info != NULL) ? info->messageId : 0;
+ responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
if(messageType != 3)
{
responseData.token = (info != NULL) ? info->token : NULL;
responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
- responseData.payload = static_cast<CAPayload_t>("response payload");
+ responseData.payload = reinterpret_cast<CAPayload_t>(const_cast<char*>("response payload"));
}
CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
responseInfo.result = static_cast<CAResponseResult_t>(respCode);
else:
casample =sample_env.Program('casample', [sample_src])
env.InstallTarget(casample, 'casample')
+env.UserInstallTargetBin(casample, 'casample')
#include "cacommon.h"
#include "cainterface.h"
-#include "oic_malloc.h"
#ifdef __WITH_DTLS__
#include "ocsecurityconfig.h"
#endif
#define SYSTEM_INVOKE_ERROR 127
#define SYSTEM_ERROR -1
-#define COAP_PREFIX "coap://"
-#define COAP_PREFIX_LEN 7
-#define COAPS_PREFIX "coaps://"
-#define COAPS_PREFIX_LEN 8
-
/**
* @def RS_IDENTITY
* @brief
void get_resource_uri(char *URI, char *resourceURI, int length);
int get_secure_information(CAPayload_t payLoad);
int get_address_set(const char *pAddress, addressSet_t* outAddress);
-void parsing_coap_uri(const char* uri, addressSet_t* address);
+void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
+CAHeaderOption_t* get_option_data(CAInfo_t* requestData);
static CAToken_t g_last_request_token = NULL;
-static const char SECURE_COAPS_PREFIX[] = "coaps://";
+
+static const char COAP_PREFIX[] = "coap://";
+static const char COAPS_PREFIX[] = "coaps://";
+static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
+static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
+
static const char SECURE_INFO_DATA[] =
"{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
- "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+ "\"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}}]}";
// create remote endpoint
CAEndpoint_t *endpoint = NULL;
+ CATransportFlags_t flags;
printf("URI : %s\n", uri);
addressSet_t address = {};
- parsing_coap_uri(uri, &address);
+ parsing_coap_uri(uri, &address, &flags);
- res = CACreateEndpoint(CA_DEFAULT_FLAGS, g_selected_nw_type,
+ res = CACreateEndpoint(flags, g_selected_nw_type,
(const char*)address.ipAddress, address.port, &endpoint);
if (CA_STATUS_OK != res || !endpoint)
{
snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
}
requestData.type = msgType;
+ CAHeaderOption_t* headerOpt = get_option_data(&requestData);
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
printf("Could not send request : %d\n", res);
}
+ if (headerOpt)
+ {
+ free(headerOpt);
+ }
+
//destroy token
CADestroyToken(token);
// destroy remote endpoint
CADestroyEndpoint(endpoint);
free(requestData.payload);
-
printf("=============================================\n");
}
{
return;
}
- snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
+ snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);
// create remote endpoint
CAEndpoint_t *endpoint = NULL;
requestData.type = CA_MSG_NONCONFIRM;
requestData.resourceUri = (CAURI_t)resourceURI;
+ CAHeaderOption_t* headerOpt = get_option_data(&requestData);
+
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
requestInfo.info = requestData;
g_last_request_token = token;
}
+ if (headerOpt)
+ {
+ free(headerOpt);
+ }
+
// destroy remote endpoint
CADestroyEndpoint(endpoint);
free(group);
int messageType = messageTypeBuf[0] - '0';
+ CATransportFlags_t flags;
addressSet_t address = {};
- parsing_coap_uri(uri, &address);
+ parsing_coap_uri(uri, &address, &flags);
// create remote endpoint
CAEndpoint_t *endpoint = NULL;
- res = CACreateEndpoint(0, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
+ res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
if (CA_STATUS_OK != res)
{
printf("Create remote endpoint error, error code: %d\n", res);
respondData.resourceUri = (CAURI_t)uri;
CAResponseInfo_t responseInfo = { 0 };
- responseInfo.result = CA_SUCCESS;
+ responseInfo.result = CA_CONTENT;
responseInfo.info = respondData;
// send request
printf("This is secure resource...\n");
//length of "coaps://"
- size_t length = sizeof(SECURE_COAPS_PREFIX) - 1;
+ size_t length = COAPS_PREFIX_LEN;
// length of "ipaddress:port"
length += strlen(object->addr) + PORT_LENGTH;
printf("Failed to create new uri\n");
return;
}
- sprintf(uri, "%s%s:%d/", SECURE_COAPS_PREFIX, object->addr,
+ sprintf(uri, "%s%s:%d/", COAPS_PREFIX, object->addr,
object->port);
CAEndpoint_t *endpoint = NULL;
object->port, &endpoint))
{
printf("Failed to create duplicate of remote endpoint!\n");
+ free(uri);
return;
}
endpoint->flags = CA_SECURE;
printf("SUCCESS : 200\n");
printf("CREATED : 201\n");
printf("DELETED : 202\n");
+ printf("VALID : 203\n");
+ printf("CHANGED : 204\n");
+ printf("CONTENT : 205\n");
printf("BAD_REQ : 400\n");
printf("BAD_OPT : 402\n");
printf("NOT_FOUND : 404\n");
CAInfo_t responseData = { 0 };
responseData.type = messageType;
responseData.messageId = (info != NULL) ? info->messageId : 0;
- responseData.resourceUri = info->resourceUri;
+ responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
if(CA_MSG_RESET != messageType)
{
printf("Memory allocation fail\n");
return;
}
- snprintf(responseData.payload, length, SECURE_INFO_DATA, info->resourceUri,
+ snprintf(responseData.payload, length, SECURE_INFO_DATA, responseData.resourceUri,
g_local_secure_port);
}
else
printf("Memory allocation fail\n");
return;
}
- snprintf(responseData.payload, length, NORMAL_INFO_DATA, info->resourceUri);
+ snprintf(responseData.payload, length, NORMAL_INFO_DATA, responseData.resourceUri);
}
}
printf("Send response success\n");
}
+ if (responseData.payload)
+ {
+ free(responseData.payload);
+ }
+
printf("=============================================\n");
}
return -1;
}
- char portStr[4] = {0};
+ char portStr[6] = {0};
memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
printf("secured port is: %s\n", portStr);
return CA_STATUS_OK;
}
-void parsing_coap_uri(const char* uri, addressSet_t* address)
+CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
+{
+ 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 NULL;
+ }
+ int optionNum = atoi(optionNumBuf);
+
+ CAHeaderOption_t * headerOpt = NULL;
+ if (0 >= optionNum)
+ {
+ printf("there is no headerOption!\n");
+ return NULL;
+ }
+ else
+ {
+ headerOpt = (CAHeaderOption_t *)calloc(1, optionNum * sizeof(CAHeaderOption_t));
+ if (NULL == headerOpt)
+ {
+ printf("Memory allocation failed!\n");
+ return NULL;
+ }
+
+ 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 NULL;
+ }
+ 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 NULL;
+ }
+
+ memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
+
+ headerOpt[i].optionLength = (uint16_t) strlen(optionData);
+ }
+ requestData->numOptions = optionNum;
+ requestData->options = headerOpt;
+ }
+ return headerOpt;
+}
+
+void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
{
if (NULL == uri)
{
{
printf("uri has '%s' prefix\n", COAPS_PREFIX);
startIndex = COAPS_PREFIX_LEN;
+ *flags = CA_SECURE;
}
else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
{
printf("uri has '%s' prefix\n", COAP_PREFIX);
startIndex = COAP_PREFIX_LEN;
+ *flags = CA_DEFAULT_FLAGS;
}
// #2. copy uri for parse
free(cloneUri);
return;
}
+ free(cloneUri);
return;
}
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')))
+
+AddOption('--prefix',
+ dest='prefix',
+ type='string',
+ nargs=1,
+ action='store',
+ metavar='DIR',
+ help='installation prefix')
+
######################################################################
# Platform(build target) specific options: SDK/NDK & toolchain
######################################################################
tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
)
else:
- env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os)
+ env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os, PREFIX = GetOption('prefix'))
Help(help_vars.GenerateHelpText(env))
def __append_target(ienv, target):
env.AppendUnique(TS = [target])
+def __installlib(ienv, targets, name):
+ user_prefix = env.get('PREFIX')
+ if user_prefix:
+ i_n = ienv.Install(user_prefix + '/lib', targets)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+ ienv.Alias("install", i_n)
+
+def __installbin(ienv, targets, name):
+ user_prefix = env.get('PREFIX')
+ if user_prefix:
+ i_n = ienv.Install(user_prefix + '/bin', targets)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+ ienv.Alias("install", i_n)
+
def __print_targets(env):
Help('''
===============================================================================
env.AddMethod(__src_to_obj, 'SrcToObj')
env.AddMethod(__append_target, 'AppendTarget')
env.AddMethod(__install, 'InstallTarget')
+env.AddMethod(__installlib, 'UserInstallTargetLib')
+env.AddMethod(__installbin, 'UserInstallTargetBin')
env.SetDir(env.GetLaunchDir())
env['ROOT_DIR']=env.GetLaunchDir()
#define RESOURCE_URI_LENGTH 14
+#define COAP_PREFIX "coap://"
+#define COAP_PREFIX_LEN 7
+#define COAPS_PREFIX "coaps://"
+#define COAPS_PREFIX_LEN 8
+
/**
* @def RS_IDENTITY
* @brief
int g_received;
uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
-CATransportType_t g_selected_nw_type = CA_IPV4;
+CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
+typedef struct
+{
+ char ipAddress[CA_IPADDR_SIZE];
+ uint16_t port;
+} addressSet_t;
+
char get_menu();
void process();
CAResult_t get_network_type();
void start_listening_server();
void start_discovery_server();
-void find_resource();
void send_request();
void send_request_all();
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 error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
-
-void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
+void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
+void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
+void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
void get_resource_uri(char *URI, char *resourceURI, int length);
int get_secure_information(CAPayload_t payLoad);
+int get_address_set(const char *uri, addressSet_t* outAddress);
+void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
static CAToken_t g_last_request_token = NULL;
static const char SECURE_COAPS_PREFIX[] = "coaps://";
start_discovery_server();
break;
- case 'f': // find resource
- case 'F':
- find_resource();
- break;
-
case 'r': // send request
case 'R':
send_request();
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();
+ send_secure_request();
while (g_received == 0)
{
sleep(1);
}
}
-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();
}
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ CATransportFlags_t flags;
+
+ printf("URI : %s\n", uri);
+ addressSet_t address = {};
+ parse_coap_uri(uri, &address, &flags);
+
+ res = CACreateEndpoint(flags, g_selected_nw_type,
+ (const char*)address.ipAddress, address.port, &endpoint);
if (CA_STATUS_OK != res || !endpoint)
{
printf("Failed to create remote endpoint, error code : %d\n", res);
char buf[MAX_BUF_LEN] = { 0 };
if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
if ((CA_STATUS_OK != res) || (!token))
{
printf("Token generate error, error code : %d\n", res);
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
printf("Generated token %s\n", token);
// extract relative resourceuri from give uri
- printf("URI : %s\n", uri);
-
- char resourceURI[15] = {0};
+ char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
+ printf("resourceURI : %s\n", resourceURI);
// create request data
CAInfo_t requestData = { 0 };
requestData.token = token;
requestData.tokenLength = tokenLength;
+ requestData.resourceUri = (CAURI_t)resourceURI;
if (strcmp(secureRequest, "1") == 0)
{
- uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+ 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);
+ CADestroyEndpoint(endpoint);
CADestroyToken(token);
return;
}
}
else
{
- uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+ 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);
+ CADestroyEndpoint(endpoint);
CADestroyToken(token);
return;
}
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
requestInfo.info = requestData;
+ requestInfo.isMulticast = false;
// send request
res = CASendRequest(endpoint, &requestInfo);
//destroy token
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
free(requestData.payload);
printf("=============================================\n");
}
+void send_secure_request()
+{
+ char ipv4addr[CA_IPADDR_SIZE];
+
+ printf("\n=============================================\n");
+ printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
+
+ if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
+ {
+ return;
+ }
+ printf("%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
+
+ // create remote endpoint
+ CAEndpoint_t *endpoint = NULL;
+ CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
+ if (CA_STATUS_OK != res)
+ {
+ printf("Failed to create remote endpoint, error code: %d\n", res);
+ goto exit;
+ }
+
+ // 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);
+ goto exit;
+ }
+
+ 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;
+
+ CARequestInfo_t requestInfo = { 0 };
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
+ requestInfo.isMulticast = false;
+
+ // send request
+ CASendRequest(endpoint, &requestInfo);
+
+exit:
+ // cleanup
+ CADestroyToken(token);
+ CADestroyEndpoint(endpoint);
+ printf("=============================================\n");
+}
+
+
void send_request_all()
{
CAResult_t res = get_network_type();
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))
+ char resourceURI[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
{
return;
}
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ res = CACreateEndpoint(0, g_selected_nw_type, NULL, 0, &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));
+ CAEndpoint_t *group = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
if (NULL == group)
{
printf("Memory allocation failed!\n");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
- group->transportType = endpoint->transportType;
- group->resourceUri = endpoint->resourceUri;
+ group->adapter = endpoint->adapter;
// create token
CAToken_t token = NULL;
if ((CA_STATUS_OK != res) || (!token))
{
printf("Token generate error!!\n");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
free(group);
return;
}
printf("generated token %s\n", token);
- CAInfo_t requestData = {CA_MSG_RESET};
+ CAInfo_t requestData = { 0 };
requestData.token = token;
requestData.tokenLength = tokenLength;
requestData.payload = "Temp Json Payload";
requestData.type = CA_MSG_NONCONFIRM;
+ requestData.resourceUri = (CAURI_t)resourceURI;
- CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
+ CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
requestInfo.info = requestData;
+ requestInfo.isMulticast = true;
- // send request all
- res = CASendRequestToAll(group, &requestInfo);
+ // send request
+ res = CASendRequest(group, &requestInfo);
if (CA_STATUS_OK != res)
{
printf("Could not send request to all\n");
}
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
free(group);
printf("=============================================\n");
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("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 : ");
- char buf[MAX_BUF_LEN] = { 0 };
- if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ char uri[MAX_BUF_LEN] = { 0 };
+ if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
{
return;
}
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 };
return;
}
+ CATransportFlags_t flags;
+ addressSet_t address = {};
+ parse_coap_uri(uri, &address, &flags);
+
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
if (CA_STATUS_OK != res)
{
printf("Create remote endpoint error, error code: %d\n", res);
if ((CA_STATUS_OK != res) || (!token))
{
printf("Token generate error!!\n");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
respondData.tokenLength = tokenLength;
respondData.payload = "Temp Notification Data";
respondData.type = messageType;
+ respondData.resourceUri = (CAURI_t)uri;
CAResponseInfo_t responseInfo = { 0 };
- responseInfo.result = CA_SUCCESS;
+ responseInfo.result = CA_CONTENT;
responseInfo.info = respondData;
// send notification
// destroy token
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
printf("\n=============================================\n");
}
{
printf("\n=============================================\n");
printf("\tselect network\n");
- printf("IPv4 : 0\n");
- printf("EDR : 2\n");
- printf("LE : 3\n");
+ printf("IP : 0\n");
+ printf("GATT : 1\n");
+ printf("RFCOMM : 2\n");
printf("select : ");
char buf[MAX_BUF_LEN] = { 0 };
{
printf("Select network success\n");
}
-
printf("=============================================\n");
}
{
printf("\n=============================================\n");
printf("\tunselect enabled network\n");
- printf("IPv4 : 0\n");
- printf("EDR : 2\n");
- printf("LE : 3\n");
+ printf("IP : 0\n");
+ printf("GATT : 1\n");
+ printf("RFCOMM : 2\n");
printf("select : ");
char buf[MAX_BUF_LEN] = { 0 };
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");
void get_network_info()
{
- CALocalConnectivity_t *tempInfo = NULL;
+ CAEndpoint_t *tempInfo = NULL;
uint32_t tempSize = 0;
CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
int index;
for (index = 0; index < tempSize; index++)
{
- printf("Type: %d\n", tempInfo[index].type);
- if (CA_IPV4 == tempInfo[index].type)
+ printf("Type: %d\n", tempInfo[index].adapter);
+ if (CA_ADAPTER_IP == tempInfo[index].adapter)
{
- printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
- printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
+ printf("Address: %s\n", tempInfo[index].addr);
+ printf("Port: %d\n", tempInfo[index].port);
}
- else if (CA_EDR == tempInfo[index].type)
+ else
{
- printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
+ printf("Address: %s\n", tempInfo[index].addr);
}
- printf("Secured: %d\n\n", tempInfo[index].isSecured);
- if (tempInfo[index].isSecured)
+ printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
+
+ if (tempInfo[index].flags & CA_SECURE)
{
- g_local_secure_port = tempInfo[index].addressInfo.IP.port;
+ g_local_secure_port = tempInfo[index].port;
printf("Secured: in global %d\n\n", g_local_secure_port);
}
}
printf("##############################################################");
}
-void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
{
if (NULL == object || NULL == requestInfo)
{
}
printf("##########received request from remote device #############\n");
- printf("Uri: %s\n", object->resourceUri);
- if (CA_IPV4 == object->transportType)
+ if (CA_ADAPTER_IP == object->adapter)
{
- printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
- object->addressInfo.IP.port, object->isSecured);
+ printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
+ object->port, object->flags & CA_SECURE);
}
- else if (CA_EDR == object->transportType)
+ else
{
- printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+ printf("Remote Address: %s \n", object->addr);
}
printf("Data: %s\n", requestInfo->info.payload);
printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
//Check if this has secure communication information
if (requestInfo->info.payload &&
- (CA_IPV4 == object->transportType))
+ (CA_ADAPTER_IP == object->adapter))
{
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;
+ 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;
+ length += strlen(object->addr) + PORT_LENGTH;
+ length += 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);
+ printf("%s%s:%d/", SECURE_COAPS_PREFIX, object->addr,
+ object->port);
- CARemoteEndpoint_t *endpoint = NULL;
- if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
+ CAEndpoint_t *endpoint = NULL;
+ if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
+ object->port, &endpoint))
{
printf("Failed to create duplicate of remote endpoint!\n");
return;
}
- endpoint->isSecured = true;
+ endpoint->flags = CA_SECURE;
object = endpoint;
-
- free(uri);
}
}
g_received = 1;
}
-void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
printf("##########Received response from remote device #############\n");
- printf("Uri: %s\n", object->resourceUri);
- if (CA_IPV4 == object->transportType)
+ if (CA_ADAPTER_IP == object->adapter)
{
- printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
- object->addressInfo.IP.port, object->isSecured);
+ printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
+ object->port, object->flags & CA_SECURE);
}
- else if (CA_EDR == object->transportType)
+ else
{
- printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+ printf("Remote Address: %s \n", object->addr);
}
+
+ printf("resource uri : %s\n", responseInfo->info.resourceUri);
printf("response result : %d\n", responseInfo->result);
printf("Data: %s\n", responseInfo->info.payload);
printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
}
}
-void error_handler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
+void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
{
printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
- if(rep && rep->resourceUri )
- {
- printf("Error Handler, RemoteEndpoint Info resourceUri : %s\n", rep->resourceUri);
- }
- else
- {
- printf("Error Handler, RemoteEndpoint is NULL");
- }
-
if(errorInfo)
{
const CAInfo_t *info = &errorInfo->info;
printf("Error Handler token : %s\n", info->token);
printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
printf("Error Handler type : %d\n", info->type);
+ printf("Error Handler resourceUri : %s\n", info->resourceUri);
printf("Error Handler payload : %s\n", info->payload);
if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
return;
}
-void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
+void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
{
printf("entering send_response\n");
printf("SUCCESS : 200\n");
printf("CREATED : 201\n");
printf("DELETED : 202\n");
+ printf("VALID : 203\n");
+ printf("CHANGED : 204\n");
+ printf("CONTENT : 205\n");
printf("BAD_REQ : 400\n");
printf("BAD_OPT : 402\n");
printf("NOT_FOUND : 404\n");
}
CAInfo_t responseData = { 0 };
responseData.type = messageType;
-
responseData.messageId = (info != NULL) ? info->messageId : 0;
+ responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
+
if(CA_MSG_RESET != messageType)
{
responseData.token = (info != NULL) ? info->token : NULL;
responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
- if (endpoint->isSecured)
+ if (endpoint->flags & CA_SECURE)
{
printf("Sending response on secure communication\n");
- uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
+ uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri)
+ + sizeof(g_local_secure_port);
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,
+ snprintf(responseData.payload, length, SECURE_INFO_DATA, responseData.resourceUri,
g_local_secure_port);
}
else
{
printf("Sending response on non-secure communication\n");
- uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
+ uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.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);
+ snprintf(responseData.payload, length, NORMAL_INFO_DATA, responseData.resourceUri);
}
}
return -1;
}
- if(((endPos - 1) - startPos) > 4)
- {
- printf("port length is not proper.Exceeding length 4\n");
- return -1;
- }
-
- char portStr[4] = {0};
+ char portStr[6] = {0};
memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
printf("secured port is: %s\n", portStr);
{
printf("\n=============================================\n");
printf("\tselect network type\n");
- printf("IPv4 : 0\n");
- printf("BT : 2\n");
- printf("LE : 3\n");
+ printf("IP : 0\n");
+ printf("GATT : 1\n");
+ printf("RFCOMM : 2\n");
printf("select : ");
char buf[MAX_BUF_LEN] = { 0 };
}
int number = buf[0] - '0';
- number = (number < 0 || number > 3) ? 0 : 1 << number;
-
- if (!(number & 0xf))
+ if (0 > number || 2 < number)
{
+ printf("\nInvalid Network type");
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");
+ g_selected_nw_type = 1 << number;
- return CA_STATUS_FAILED;
+ return CA_STATUS_OK;
}
CAResult_t get_input_data(char *buf, int32_t length)
return CA_STATUS_OK;
}
+
+
+void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
+{
+ if (NULL == uri)
+ {
+ printf("parameter is null\n");
+ return;
+ }
+
+ // parse uri
+ // #1. check prefix
+ uint8_t startIndex = 0;
+ if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
+ {
+ printf("uri has '%s' prefix\n", COAPS_PREFIX);
+ startIndex = COAPS_PREFIX_LEN;
+ *flags = CA_SECURE;
+ }
+ else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
+ {
+ printf("uri has '%s' prefix\n", COAP_PREFIX);
+ startIndex = COAP_PREFIX_LEN;
+ *flags = CA_DEFAULT_FLAGS;
+ }
+
+ // #2. copy uri for parse
+ int32_t len = strlen(uri) - startIndex;
+
+ if (len <= 0)
+ {
+ printf("uri length is 0!\n");
+ return;
+ }
+
+ int res = get_address_set(uri + startIndex, address);
+ if (res == -1)
+ {
+ printf("address parse error\n");
+ return;
+ }
+
+ return;
+}
+
+int get_address_set(const char *uri, addressSet_t* outAddress)
+{
+ if (NULL == uri || NULL == outAddress)
+ {
+ printf("parameter is null !\n");
+ return -1;
+ }
+
+ int32_t len = strlen(uri);
+ if (len <= 0)
+ {
+ printf("uri length is 0!\n");
+ return -1;
+ }
+
+ int32_t isIp = 0;
+ int32_t ipLen = 0;
+ for (int i = 0; i < len; i++)
+ {
+ if (uri[i] == '.')
+ {
+ isIp = 1;
+ }
+
+ // found port number start index
+ if (isIp && uri[i] == ':')
+ {
+ ipLen = i;
+ outAddress->port = atoi(uri + ipLen + 1);
+ break;
+ }
+
+ if (uri[i] == '/')
+ {
+ break;
+ }
+
+ outAddress->ipAddress[i] = uri[i];
+ }
+
+ return isIp;
+}
# CA build script
##
+import os.path
+
Import('env')
ca_os = env.get('TARGET_OS')
ca_transport = env.get('TARGET_TRANSPORT')
secured = env.get('SECURED')
-root_dir = './../'
-ca_path = './'
-if ca_os == 'tizen':
- current_dir = root_dir
-else:
- 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 ='../../../../../../../../'
+root_dir = os.pardir
+ca_path = os.curdir
#####################################################################
# 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/'])
+env.PrependUnique(CPPPATH = [ os.path.join(root_dir, 'api') ])
+env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'inc'),
+ os.path.join(root_dir, 'lib/libcoap-4.1.1'),
+ os.path.join(root_dir, 'common/inc') ])
if ca_os not in ['arduino', 'windows', 'winrt']:
env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
if ca_os in ['darwin','ios']:
env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
-#Getting common source files
+# Getting common source files
env.SConscript('./../common/SConscript')
+# The tinydtls library is found in '#extlibs/tinydtls', where the '#'
+# is interpreted by SCons as the top-level iotivity directory where
+# the SConscruct file is found.
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')
+ if ca_os == 'tizen':
+ env.SConscript(os.path.join(root_dir, 'extlibs/tinydtls/SConscript'))
+ else:
+ env.SConscript('#extlibs/tinydtls/SConscript')
+env.AppendUnique(CA_SRC = [os.path.join(ca_path,
+ 'adapter_util/caadapterutils.c')])
+env.AppendUnique(CA_SRC = [os.path.join(ca_path,
+ 'adapter_util/cafragmentation.c')])
-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/'])
+ env.AppendUnique(CA_SRC = [os.path.join(ca_path,
+ 'adapter_util/caadapternetdtls.c')])
+ env.AppendUnique(CPPPATH = [os.path.join(root_dir,
+ 'external/inc')])
+ca_common_src = None
if ca_os == 'arduino':
env.AppendUnique(CPPDEFINES = ['SINGLE_THREAD'])
env.AppendUnique(CPPDEFINES = ['WITH_ARDUINO'])
print "setting WITH_ARDUINO"
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',
+ 'caconnectivitymanager.c',
+ 'cainterfacecontroller.c',
+ 'camessagehandler_singlethread.c',
+ 'canetworkconfigurator.c',
+ 'caprotocolmessage.c',
+ 'caretransmission.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',
+ 'caconnectivitymanager.c',
+ 'cainterfacecontroller.c',
+ 'camessagehandler.c',
+ 'canetworkconfigurator.c',
+ 'caprotocolmessage.c',
+ 'caqueueingthread.c',
+ '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'])
+ if ca_os == 'tizen':
+ env.AppendUnique(CPPPATH = [os.path.join(root_dir, 'extlibs/tinydtls')])
+ else:
+ env.AppendUnique(CPPPATH = ['#extlibs/tinydtls'])
+
+ca_common_src = [
+ os.path.join(ca_path, d) for d in ca_common_src ]
+
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')
+ transports = [ 'ip_adapter', 'bt_edr_adapter', 'bt_le_adapter' ]
+ env.SConscript(dirs = [
+ os.path.join(ca_path, d) for d in transports ])
if 'IP' in ca_transport:
- env.SConscript(ca_path + 'ip_adapter/SConscript')
+ env.SConscript(os.path.join(ca_path, 'ip_adapter/SConscript'))
if 'BT' in ca_transport:
- env.SConscript(ca_path + 'bt_edr_adapter/SConscript')
+ env.SConscript(os.path.join(ca_path, 'bt_edr_adapter/SConscript'))
if 'BLE' in ca_transport:
- env.SConscript(ca_path + 'bt_le_adapter/SConscript')
+ env.SConscript(os.path.join(ca_path, 'bt_le_adapter/SConscript'))
-print "Include path is %s" %env.get('CPPPATH')
-print "Files path is %s" %env.get('CA_SRC')
+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')
+env.UserInstallTargetLib(calib, 'libconnectivity_abstraction')
static CAResult_t CAAddIdToPeerInfoList(const char *peerAddr, uint32_t port,
const unsigned char *id, uint16_t id_length)
{
- if(NULL == peerAddr || NULL == id || 0 == port || 0 == id_length)
+ if(NULL == peerAddr
+ || NULL == id
+ || 0 == port
+ || 0 == id_length
+ || CA_MAX_ENDPOINT_IDENTITY_LEN < id_length)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "CAAddIdToPeerInfoList invalid parameters");
return CA_STATUS_INVALID_PARAM;
OICStrcpy(peer->addr, sizeof(peer->addr), peerAddr);
peer->port = port;
- OICStrcpyPartial(peer->identity.id, sizeof(peer->identity.id), id, id_length);
+
+ memcpy(peer->identity.id, id, id_length);
peer->identity.id_length = id_length;
if(NULL != GetPeerInfo(peer))
OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - token : %s", pdu->hdr->token);
}
-CAEndpoint_t *CAAdapterCreateEndpoint(CATransportFlags_t flags,
- CATransportAdapter_t adapter,
- const char *address,
- uint16_t port)
-{
- VERIFY_NON_NULL_RET(address, CA_ADAPTER_UTILS_TAG, "Endpoint is NULL", NULL);
- CAEndpoint_t *info = (CAEndpoint_t *)OICCalloc(1, sizeof(CAEndpoint_t));
- if (NULL == info)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
- return NULL;
- }
-
- OICStrcpy(info->addr, sizeof(info->addr), address);
- info->addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
- info->flags = flags;
- info->adapter = adapter;
- info->port = port;
-
- return info;
-}
-
-CAEndpoint_t *CAAdapterCreateLocalEndpoint(CATransportFlags_t flags,
- CATransportAdapter_t adapter, const char *address)
-{
- return CAAdapterCreateEndpoint(flags, adapter, address, 0);
-}
-
-CAResult_t CACreateEndpoint(CATransportFlags_t flags,
- CATransportAdapter_t adapter,
- const CAURI_t uri,
- uint16_t port,
- CAEndpoint_t **object)
-{
- VERIFY_NON_NULL_RET(object, CA_ADAPTER_UTILS_TAG, "Endpoint is NULL", CA_STATUS_INVALID_PARAM);
- CAEndpoint_t *endpoint = CAAdapterCreateEndpoint(flags, adapter, uri, port);
- if (!endpoint)
- {
- return CA_STATUS_FAILED;
- }
- *object = endpoint;
- return CA_STATUS_OK;
-}
-
-
-CAEndpoint_t *CAAdapterCloneEndpoint(const CAEndpoint_t *endpoint)
-{
- VERIFY_NON_NULL_RET(endpoint, CA_ADAPTER_UTILS_TAG, "endpoint is NULL", NULL);
-
- CAEndpoint_t *info = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
- if (NULL == info)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
- return NULL;
- }
- *info = *endpoint;
-
- return info;
-}
-
-void CAAdapterFreeEndpoint(CAEndpoint_t *remoteEndpoint)
-{
- OICFree(remoteEndpoint);
-}
CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
size_t ipAddrLen, uint16_t *port)
return g_jvm;
}
#endif
-
*
******************************************************************/
-#include "camsgparser.h"
-
#include <string.h>
#include <math.h>
#include "cacommon.h"
#include "caadapterutils.h"
+#include "cafragmentation.h"
/**
- * @var CA_MSG_PARSER_TAG
- * @brief debugging tag for parser module
+ * @var CA_FRAGMENTATION_TAG
+ * @brief debugging tag for fragmentation module
*/
-#define CA_MSG_PARSER_TAG "CA_MSG_PARSER"
+#define CA_FRAGMENTATION_TAG "CA_FRAGMENTATION"
CAResult_t CAGenerateHeader(char *header, uint32_t length)
{
- OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "IN");
+ OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "IN");
- VERIFY_NON_NULL(header, CA_MSG_PARSER_TAG, "header is NULL");
+ VERIFY_NON_NULL(header, CA_FRAGMENTATION_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");
+ OIC_LOG(DEBUG, CA_FRAGMENTATION_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;
header[0] = length & 0x0F;
header[0] = header[0] | 0x40; // Adding version 0100.(Not used. Future use)
- OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "OUT");
+ OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "OUT");
+
return CA_STATUS_OK;
}
uint32_t CAParseHeader(const char *header)
{
- OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "IN");
+ OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "IN");
- VERIFY_NON_NULL(header, CA_MSG_PARSER_TAG, "header is NULL");
+ VERIFY_NON_NULL_RET(header, CA_FRAGMENTATION_TAG, "header is NULL", 0);
uint32_t dataLen = ((header[0] & 0x0F) << 8) | (header[1] & 0xFF);
- OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "OUT");
+ OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "OUT");
return dataLen;
}
-
#######################################################
-# Building BT adapter
+# Build BT EDR adapter
#######################################################
Import('env')
+import os.path
-print"Reading bt adapter script"
+print "Reading BT EDR adapter script"
target_os = env.get('TARGET_OS')
-if target_os == 'tizen':
- env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
+src_dir = os.path.join(os.curdir, 'bt_edr_adapter')
-src_dir = './bt_edr_adapter/'
-
-#Source files to build common for all platforms
+# Source files to build common for all platforms
+common_files = []
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',
- ])
-
+ common_files = [ os.path.join(src_dir, 'caedradapter.c') ]
+
+# Get list of target-specific source file base names, i.e. no parent
+# directories prepended to the path.
+#
+# Target-specific SConscript files are expected to return that list.
+target_files = []
+target_sconscript = os.path.join(target_os, 'SConscript')
+
+# Check for the existence of the platform-specific SConscript file
+# relative to the top-level source directory, not the build (variant)
+# directory, before calling that SConscript file to prevent a missing
+# file warning platforms that don't provide one.
+target_sconscript_abspath = str(File(target_sconscript).srcnode().abspath)
+if os.path.exists(target_sconscript_abspath):
+ target_files = env.SConscript(target_sconscript, exports='src_dir')
+
+# Now prepend the appropriate parent directories
+# (e.g. ./bt_edr_adapter/linux) to each of the target source files in
+# the list.
+target_files = [ os.path.join(src_dir, target_os, f) for f in target_files ]
+
+# The list of BLE adapter source files is a combination of both the
+# common and target-specific source file lists.
+env.AppendUnique(CA_SRC = common_files + target_files)
--- /dev/null
+#######################################################
+# Build BT EDR adapter for Android
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'android') ])
+
+src_files = [ 'caedrclient.c',
+ 'caedrutils.c',
+ 'caedrnwmonitor.c',
+ 'caedrserver.c', ]
+
+Return('src_files')
#include "camutex.h"
#include "uarraylist.h"
#include "caadapterutils.h"
+#include "caremotehandler.h"
//#define DEBUG_MODE
#define TAG PCF("CA_EDR_CLIENT")
*/
static ca_mutex g_mutexObjectList = NULL;
+/**
+ * @var g_edrErrorHandler
+ * @brief Error callback to update error in EDR
+ */
+static CAEDRErrorHandleCallback g_edrErrorHandler = NULL;
+
typedef struct send_data
{
char* address;
}
// Create local endpoint using util function
- CAEndpoint_t *endpoint = CAAdapterCreateEndpoint(CA_DEFAULT_FLAGS,
- CA_ADAPTER_RFCOMM_BTEDR, macAddress, 0);
+ CAEndpoint_t *endpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_RFCOMM_BTEDR,
+ macAddress, 0);
if (NULL == endpoint)
{
OIC_LOG(ERROR, TAG, "Failed to create Local Endpoint!");
{
OIC_LOG(ERROR, TAG, "Invalid input..");
OICFree(macAddress);
- CAAdapterFreeEndpoint(endpoint);
+ CAFreeEndpoint(endpoint);
return CA_MEMORY_ALLOC_FAILED;
}
*netInfo = *endpoint;
*info = netInfo;
OICFree(macAddress);
- CAAdapterFreeEndpoint(endpoint);
+ CAFreeEndpoint(endpoint);
OIC_LOG(DEBUG, TAG, "OUT - CAEDRGetInterfaceInformation");
return CA_STATUS_OK;
const void *data, uint32_t dataLength, uint32_t *sentLength)
{
OIC_LOG(DEBUG, TAG, "IN");
- CAEDRSendUnicastMessage(remoteAddress, (const char*) data, dataLength);
+ CAResult_t result = CAEDRSendUnicastMessage(remoteAddress, (const char*) data, dataLength);
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+ return result;
}
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);
+ CAResult_t result = CAEDRSendMulticastMessage((const char*) data, dataLength);
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+ return result;
}
// It will be updated when android EDR support is added
{
OIC_LOG_V(DEBUG, TAG, "CAEDRSendUnicastMessage(%s, %s)", address, data);
- CAEDRSendUnicastMessageImpl(address, data, dataLen);
- return CA_STATUS_OK;
+ CAResult_t result = CAEDRSendUnicastMessageImpl(address, data, dataLen);
+ return result;
}
CAResult_t CAEDRSendMulticastMessage(const char* data, uint32_t dataLen)
isAttached = true;
}
- CAEDRSendMulticastMessageImpl(env, data, dataLen);
+ CAResult_t result = CAEDRSendMulticastMessageImpl(env, data, dataLen);
+ if(CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, TAG, "CAEDRSendMulticastMessage - could not send multicast message");
+ return result;
+ }
OIC_LOG(DEBUG, TAG, "sent data");
(*env)->ReleaseStringUTFChars(env, j_str_address, remoteAddress);
if (CA_STATUS_OK != res)
{
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] Send data has failed : %s", remoteAddress);
+ OIC_LOG_V(ERROR, TAG, "CASendMulticastMessageImpl, failed to send message to : %s",
+ remoteAddress);
+ g_edrErrorHandler(remoteAddress, OIC_EDR_SERVICE_ID, data, dataLen, res);
continue;
}
}
CAEDRInitialize(handle);
OIC_LOG(DEBUG, TAG, "OUT");
}
+
+void CAEDRSetErrorHandler(CAEDRErrorHandleCallback errorHandleCallback)
+{
+ g_edrErrorHandler = errorHandleCallback;
+}
OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: read %s, %d", buf, length);
char responseData[MAX_PDU_BUFFER] = { 0 };
- OICStrcpy(responseData, sizeof(responseData), buf, length);
+ memcpy(responseData, (const char*) buf, length);
switch (type)
{
#include "caedrinterface.h"
#include "caadapterutils.h"
#include "logger.h"
-#include "camsgparser.h"
+#include "cafragmentation.h"
#include "caqueueingthread.h"
#include "oic_malloc.h"
+#include "caremotehandler.h"
/**
* @var EDR_ADAPTER_TAG
static CANetworkChangeCallback g_networkChangeCallback = NULL;
/**
+ * @var g_errorCallback
+ * @brief error Callback to CA adapter
+ */
+static CAErrorHandleCallback g_errorCallback = NULL;
+
+/**
* @var g_localConnectivity
* @brief Information of local Bluetooth adapter.
*/
static void CAEDRDataDestroyer(void *data, uint32_t size);
+static void CAEDRErrorHandler(const char *remoteAddress, const char *serviceUUID, const void *data,
+ uint32_t dataLength, CAResult_t result);
+
CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
CANetworkPacketReceivedCallback packetReceivedCallback,
CANetworkChangeCallback networkStateChangeCallback,
- ca_thread_pool_t handle)
+ CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
g_edrThreadPool = handle;
g_networkPacketReceivedCallback = packetReceivedCallback;
g_networkChangeCallback = networkStateChangeCallback;
+ g_errorCallback = errorCallback;
// Initialize EDR Network Monitor
CAResult_t err = CAEDRInitializeNetworkMonitor(handle);
CAEDRSetNetworkChangeCallback(CAEDRNotifyNetworkStatus);
CAEDRSetPacketReceivedCallback(CAAdapterRecvData);
+ CAEDRSetErrorHandler(CAEDRErrorHandler);
CAEDRInitializeClient(handle);
CAConnectivityHandler_t handler;
if (CA_STATUS_OK != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Send unicast data failed!, error num [%d]", err);
+ g_errorCallback(remoteEndpoint, data, dataLength, err);
return -1;
}
if (CA_STATUS_OK != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Send multicast data failed!, error num [%d]", err);
+ g_errorCallback(endpoint, data, dataLength, err);
return -1;
}
CAEDRServerTerminate();
// Free LocalConnectivity information
- CAAdapterFreeEndpoint(g_localConnectivity);
+ CAFreeEndpoint(g_localConnectivity);
g_localConnectivity = NULL;
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
if (NULL == message->remoteEndpoint)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "remoteEndpoint is not available");
+ return;
}
else
{
remoteAddress = message->remoteEndpoint->addr;
}
+ if(!remoteAddress || !serviceUUID)
+ {
+ OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDR Send Message error");
+ //Error cannot be sent if remote address is NULL
+ return;
+ }
+
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",
if (NULL == dataSegment)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed");
+ CAEDRErrorHandler(remoteAddress, serviceUUID, message->data, message->dataLen, CA_SEND_FAILED);
OICFree(header);
return;
}
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Generate header failed");
OICFree(header);
OICFree(dataSegment);
+ CAEDRErrorHandler(remoteAddress, serviceUUID, message->data, message->dataLen, CA_SEND_FAILED);
return ;
}
uint32_t iter = dataSegmentLength / CA_SUPPORTED_EDR_MTU_SIZE;
uint32_t index = 0;
- if (CA_STATUS_OK != CAEDRClientSendData(remoteAddress, serviceUUID, dataSegment, length,
- &sentLength))
+ result = CAEDRClientSendData(remoteAddress, serviceUUID, dataSegment, length,
+ &sentLength);
+ if(CA_STATUS_OK != result)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAEDRClientSendData API failed");
OICFree(dataSegment);
+ CAEDRErrorHandler(remoteAddress, serviceUUID, message->data, message->dataLen, result);
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))
+ void *dataPtr = message->data + ((index * CA_SUPPORTED_EDR_MTU_SIZE) - CA_HEADER_LENGTH);
+ result = CAEDRClientSendData(remoteAddress, serviceUUID,
+ dataPtr, CA_SUPPORTED_EDR_MTU_SIZE, &sentLength);
+ if(CA_STATUS_OK != result)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAEDRClientSendData API failed");
+ CAEDRErrorHandler(remoteAddress, serviceUUID, message->data, message->dataLen, result);
return;
}
}
{
// 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))
+ void *dataPtr = message->data + ((index * CA_SUPPORTED_EDR_MTU_SIZE) - CA_HEADER_LENGTH);
+ result = CAEDRClientSendData(remoteAddress, serviceUUID, dataPtr,
+ remainingLen, &sentLength);
+ if(CA_STATUS_OK != result)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAEDRClientSendData API failed");
+ CAEDRErrorHandler(remoteAddress, serviceUUID, message->data, message->dataLen, result);
return;
}
}
const void *data, uint32_t dataLength, uint32_t *sentLength)
{
+ CAResult_t result = CA_SEND_FAILED;
+
// 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))
+ result = CAEDRClientSendUnicastData(remoteAddress, serviceUUID, data,
+ dataLength, sentLength);
+ if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to send unicast data !");
- return CA_STATUS_FAILED;
+ return result;
}
}
else
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "sending multicast data : %s", data);
- if (CA_STATUS_OK != CAEDRClientSendMulticastData(serviceUUID, data, dataLength,
- sentLength))
+ result = CAEDRClientSendMulticastData(serviceUUID, data, dataLength,
+ sentLength);
+
+ if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to send multicast data !");
- return CA_STATUS_FAILED;
+ return result;
}
}
- return CA_STATUS_OK;
+ return result;
}
void CAAdapterDataReceiverHandler(void *context)
}
const char *remoteAddress = message->remoteEndpoint->addr;
- uint16_t port = message->remoteEndpoint->port;
- remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_RFCOMM_BTEDR, remoteAddress, port);
+ remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_RFCOMM_BTEDR,
+ remoteAddress, 0);
memcpy(defragData + recvDataLen, message->data + CA_HEADER_LENGTH,
message->dataLen - CA_HEADER_LENGTH);
VERIFY_NON_NULL_VOID(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
// Create remote endpoint
- CAEndpoint_t *remoteEndpoint = CAAdapterCreateEndpoint(0,
- CA_ADAPTER_RFCOMM_BTEDR,
- remoteAddress,
- 0);
+ CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
+ CA_ADAPTER_RFCOMM_BTEDR,
+ remoteAddress, 0);
if (NULL == remoteEndpoint)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
*sentLength = dataLength;
// Free remote endpoint
- CAAdapterFreeEndpoint(remoteEndpoint);
+ CAFreeEndpoint(remoteEndpoint);
+
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAEDRErrorHandler(const char *remoteAddress, const char *serviceUUID, const void *data,
+ uint32_t dataLength, CAResult_t result)
+{
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+ // Input validation
+ VERIFY_NON_NULL_VOID(data, EDR_ADAPTER_TAG, "Data is null");
+
+ // Create remote endpoint
+ CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(0, CA_ADAPTER_RFCOMM_BTEDR,
+ remoteAddress, 0);
+ if (!remoteEndpoint)
+ {
+ OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
+ return;
+ }
+
+ g_errorCallback(remoteEndpoint, data, dataLength, result);
+
+ // Free remote endpoint
+ CAFreeEndpoint(remoteEndpoint);
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
*sentLength = 0;
- return CA_STATUS_OK;
+ return CA_ADAPTER_NOT_ENABLED;
}
// Input validation
VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "service UUID is null");
VERIFY_NON_NULL(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
// Create remote endpoint
- CAEndpoint_t *remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_RFCOMM_BTEDR, remoteAddress, 0);
+ CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
+ CA_ADAPTER_RFCOMM_BTEDR,
+ remoteAddress, 0);
if (NULL == remoteEndpoint)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
- return CA_STATUS_FAILED;
+ return CA_MEMORY_ALLOC_FAILED;
}
// Add message to data queue
*sentLength = dataLength;
// Free remote endpoint
- CAAdapterFreeEndpoint(remoteEndpoint);
+ CAFreeEndpoint(remoteEndpoint);
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT - CAAdapterSendData");
return CA_STATUS_OK;
}
// Create duplicate of Local connectivity
- event->info = CAAdapterCloneEndpoint(connectivity);
+ event->info = CACloneEndpoint(connectivity);
event->status = status;
return event;
}
{
if (event)
{
- CAAdapterFreeEndpoint(event->info);
+ CAFreeEndpoint(event->info);
OICFree(event);
}
}
return NULL;
}
- edrData->remoteEndpoint = CAAdapterCloneEndpoint(remoteEndpoint);
+ edrData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
edrData->data = OICMalloc(dataLength);
if (NULL == edrData->data)
{
VERIFY_NON_NULL_VOID(edrData, EDR_ADAPTER_TAG, "edrData is NULL");
- CAAdapterFreeEndpoint(edrData->remoteEndpoint);
+ CAFreeEndpoint(edrData->remoteEndpoint);
OICFree(edrData->data);
OICFree(edrData);
}
--- /dev/null
+##########################################
+# Build BT EDR adapter for Linux
+##########################################
+
+Import('env')
+
+src_files = [ 'caedradapter.c']
+
+Return('src_files')
static ca_thread_pool_t g_threadPoolHandle = NULL;
CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
- CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
- ca_thread_pool_t handle)
+ CANetworkPacketReceivedCallback reqRespCallback,
+ CANetworkChangeCallback networkStateChangeCallback,
+ CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "CAInitializeEDR");
--- /dev/null
+#######################################################
+# Build BT EDR adapter for Tizen
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'tizen'),
+ './con/lib/tizen/ble/inc',
+ './con/lib/tizen/ble/inc/mobile' ])
+
+env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
+
+src_files = [ 'caedrclient.c',
+ 'caedrdevicelist.c',
+ 'caedrendpoint.c',
+ 'caedrnwmonitor.c',
+ 'caedrserver.c',
+ 'caedrutils.c' ]
+
+Return('src_files')
static CAEDRDataReceivedCallback g_edrPacketReceivedCallback = NULL;
/**
+ * @var g_edrErrorHandler
+ * @brief Error callback to update error in EDR
+ */
+static CAEDRErrorHandleCallback g_edrErrorHandler = NULL;
+/**
* @fn CAEDRManagerInitializeMutex
* @brief This function creates mutex.
*/
g_edrPacketReceivedCallback = packetReceivedCallback;
}
+void CAEDRSetErrorHandler(CAEDRErrorHandleCallback errorHandleCallback)
+{
+ g_edrErrorHandler = errorHandleCallback;
+}
+
void CAEDRSocketConnectionStateCallback(int result, bt_socket_connection_state_e state,
bt_socket_connection_s *connection, void *userData)
{
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "sending data failed!, soketid [%d]", serverFD);
*sentDataLen = 0;
- return CA_STATUS_FAILED;
+ return CA_SOCKET_OPERATION_FAILED;
}
*sentDataLen = dataLen;
#include "caedrutils.h"
#include "caadapterutils.h"
#include "caqueueingthread.h"
+#include "caremotehandler.h"
/**
* @var g_edrNetworkChangeCallback
g_edrNetworkChangeCallback = networkChangeCallback;
}
-CAResult_t CAEDRGetInterfaceInformation(CALocalConnectivity_t **info)
+CAResult_t CAEDRGetInterfaceInformation(CAEndpoint_t **info)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
}
// Create network info
- *info = CAAdapterCreateLocalEndpoint(CA_EDR, localAddress);
+ *info = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_RFCOMM_BTEDR, localAddress, 0);
if (NULL == *info)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create LocalConnectivity instance!");
-#######################################################
-# Building BLE adapter
-#######################################################
+################################
+# Build BLE adapter
+################################
Import('env')
-
-print"Reading ble adapter script"
+import os.path
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'
- ])
+print "Reading BLE adapter script for", target_os
+
+src_dir = os.path.join(os.curdir, 'bt_le_adapter')
+
+# Source files to build common for all platforms.
+common_files = None
+common_files = [ os.path.join(src_dir,
+ 'caleadapter.c') ]
+
+
+# Get list of target-specific source file base names, i.e. no parent
+# directories prepended to the path.
+#
+# Target-specific SConscript files are expected to return that list.
+target_files = []
+target_sconscript = os.path.join(target_os, 'SConscript')
+
+# Check for the existence of the platform-specific SConscript file
+# relative to the top-level source directory, not the build (variant)
+# directory, before calling that SConscript file to prevent a missing
+# file warning platforms that don't provide one.
+target_sconscript_abspath = str(File(target_sconscript).srcnode().abspath)
+if os.path.exists(target_sconscript_abspath):
+ target_files = env.SConscript(target_sconscript, exports='src_dir')
+
+# Now prepend the appropriate parent directories
+# (e.g. ./bt_le_adapter/linux) to each of the target source files in
+# the list.
+target_files = [ os.path.join(src_dir, target_os, f) for f in target_files ]
+
+# The list of BLE adapter source files is a combination of both the
+# common and target-specific source file lists.
+env.AppendUnique(CA_SRC = common_files + target_files)
+
--- /dev/null
+#######################################################
+# Build BLE adapter for Android
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'android') ])
+
+src_files = [ 'caleclient.c',
+ 'caleserver.c',
+ 'calenwmonitor.c',
+ 'caleutils.c' ]
+
+Return('src_files')
static u_arraylist_t *g_deviceStateList = NULL;
static CAPacketReceiveCallback g_packetReceiveCallback = NULL;
+static CABLEErrorHandleCallback g_clientErrorCallback;
static ca_thread_pool_t g_threadPoolHandle = NULL;
static jobject g_leScanCallback = NULL;
static jobject g_leGattCallback = 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_SendFinishMutex = NULL;
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;
// init mutex for send logic
g_threadCond = ca_cond_new();
- g_threadSendCond = ca_cond_new();
- g_threadSendCBCond = ca_cond_new();
CALEClientCreateDeviceList();
CALEClientJNISetContext();
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_packetReceiveCallback = callback;
}
+void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
+{
+ g_clientErrorCallback = callback;
+}
+
CAResult_t CALEClientGetInterfaceInfo(char **address)
{
OIC_LOG(INFO, TAG, "CALEClientGetInterfaceInfo is not supported");
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;
{
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)
if (CA_STATUS_OK != res)
{
OIC_LOG_V(INFO, TAG, "multicast : send has failed for this device[%s]", address);
+ g_clientErrorCallback(address, data, dataLen, res);
(*env)->ReleaseStringUTFChars(env, jni_address, address);
continue;
}
// scan gatt server with UUID
if (g_leScanCallback && g_uuidList)
{
-#ifndef FULL_SCAN
+#ifdef UUID_SCAN
ret = CALEClientStartScanWithUUIDImpl(env, g_uuidList, g_leScanCallback);
if(CA_STATUS_OK != ret)
{
if (!jni_obj_character)
{
CALEClientSendFinish(env, gatt);
- ca_cond_signal(g_threadSendCond);
return CA_STATUS_FAILED;
}
if (CA_STATUS_OK != ret)
{
CALEClientSendFinish(env, gatt);
- ca_cond_signal(g_threadSendCond);
return ret;
}
}
}
- 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_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;
}
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");
}
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 CAStartLEGattClient()
{
CAResult_t res = CALEClientStartMulticastServer();
if (CA_STATUS_OK != res)
return res;
}
-void CAStopBLEGattClient()
+void CAStopLEGattClient()
{
OIC_LOG(DEBUG, TAG, "CAStopBLEGattClient");
}
ca_cond_signal(g_threadCond);
- ca_cond_signal(g_threadSendCond);
- g_isStartedLEClient = false;
if (isAttached)
{
}
-void CATerminateBLEGattClient()
+void CATerminateLEGattClient()
{
OIC_LOG(DEBUG, TAG, "Terminate GATT Client");
CALEClientTerminate();
return CALEClientSendMulticastMessage(data, dataLen);
}
-void CASetBLEReqRespClientCallback(CABLEClientDataReceivedCallback callback)
+void CASetLEReqRespClientCallback(CABLEClientDataReceivedCallback callback)
{
OIC_LOG(DEBUG, TAG, "IN");
OIC_LOG(DEBUG, TAG, "OUT");
}
-void CASetBleClientThreadPoolHandle(ca_thread_pool_t handle)
+void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "IN");
{
OIC_LOG(ERROR, TAG, "CALEClientGattClose has failed");
}
-
- ca_cond_signal(g_threadSendCond);
}
else // error
{
}
(*env)->ReleaseStringUTFChars(env, jni_address, address);
+ CAResult_t res = CALEClientGattClose(env, gatt);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "CALEClientGattClose has failed");
+ }
+
goto error_exit;
}
return;
error_exit:
CALEClientSendFinish(env, gatt);
- ca_cond_signal(g_threadSendCond);
return;
}
if (0 != status) // discovery error
{
CALEClientSendFinish(env, gatt);
- ca_cond_signal(g_threadSendCond);
return;
}
if (!jni_address)
{
CALEClientSendFinish(env, gatt);
- ca_cond_signal(g_threadSendCond);
return;
}
if (!address)
{
CALEClientSendFinish(env, gatt);
- ca_cond_signal(g_threadSendCond);
return;
}
error_exit:
(*env)->ReleaseStringUTFChars(env, jni_address, address);
CALEClientSendFinish(env, gatt);
- ca_cond_signal(g_threadSendCond);
return;
}
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);
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;
}
error_exit:
CALEClientSendFinish(env, gatt);
- ca_cond_signal(g_threadSendCond);
return;
}
*/
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
static jobject g_leAdvertiseCallback = NULL;
static CAPacketReceiveCallback g_packetReceiveCallback = NULL;
+static CABLEErrorHandleCallback g_serverErrorCallback;
+
static u_arraylist_t *g_connectedDeviceList = NULL;
static ca_thread_pool_t g_threadPoolHandle = NULL;
jfieldID jni_fid_readProperties = (*env)->GetStaticFieldID(env,
jni_cid_bluetoothGattCharacteristic,
- "PROPERTY_READ", "I");
+ "PROPERTY_NOTIFY", "I");
if (!jni_fid_readProperties)
{
OIC_LOG(ERROR, TAG, "jni_fid_readProperties is null");
jni_cid_bluetoothGattCharacteristic,
jni_fid_readPermissions);
+ jint jni_int_writePermissions = (*env)->GetStaticIntField(env,
+ jni_cid_bluetoothGattCharacteristic,
+ jni_fid_writePermissions);
+
jobject jni_readCharacteristic = (*env)->NewObject(env, jni_cid_bluetoothGattCharacteristic,
jni_mid_bluetoothGattCharacteristic,
jni_obj_readUuid, jni_int_readProperties,
- jni_int_readPermissions);
+ jni_int_readPermissions|
+ jni_int_writePermissions);
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)
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,
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)
{
return CA_STATUS_OK;
}
+CAResult_t CALEServerGattClose(JNIEnv *env, jobject bluetoothGattServer)
+{
+ // GATT CLOSE
+ OIC_LOG(DEBUG, TAG, "GattServer Close");
+ VERIFY_NON_NULL(bluetoothGattServer, TAG, "bluetoothGattServer 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, "android/bluetooth/BluetoothGattServer");
+ 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, bluetoothGattServer, 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 CALEServerSend(JNIEnv *env, jobject bluetoothDevice, jbyteArray responseData)
{
OIC_LOG(DEBUG, TAG, "IN - CALEServerSend");
ret = CALEServerStartAdvertise(env, g_leAdvertiseCallback);
if (CA_STATUS_OK != ret)
{
- OIC_LOG(ERROR, TAG, "CALEServerSendMulticastMessageImpl has failed");
+ OIC_LOG(ERROR, TAG, "CALEServerStartAdvertise has failed");
}
if (isAttached)
CAResult_t ret = CALEServerStopAdvertise(env, g_leAdvertiseCallback);
if (CA_STATUS_OK != ret)
{
- OIC_LOG(ERROR, TAG, "CALEServerSendMulticastMessageImpl has failed");
+ OIC_LOG(ERROR, TAG, "CALEServerStopAdvertise has failed");
}
g_isStartServer = false;
else if (newState == jni_int_state_disconnected)
{
OIC_LOG(DEBUG, TAG, "LE DISCONNECTED");
+ CAResult_t res = CALEServerGattClose(env, g_bluetoothGattServer);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "CALEServerGattClose has failed");
+ }
}
else
{
* adapter common
*/
-CAResult_t CAStartBleGattServer()
+CAResult_t CAStartLEGattServer()
{
OIC_LOG(DEBUG, TAG, "IN");
return CA_STATUS_OK;
}
-CAResult_t CAStopBleGattServer()
+CAResult_t CAStopLEGattServer()
{
OIC_LOG(DEBUG, TAG, "IN");
return CA_STATUS_OK;
}
-void CATerminateBleGattServer()
+void CATerminateLEGattServer()
{
OIC_LOG(DEBUG, TAG, "IN");
OIC_LOG(DEBUG, TAG, "OUT");
}
-void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback)
+void CASetLEReqRespServerCallback(CABLEServerDataReceivedCallback callback)
{
OIC_LOG(DEBUG, TAG, "IN");
OIC_LOG(DEBUG, TAG, "OUT");
}
+void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback)
+{
+ g_serverErrorCallback = callback;
+}
+
CAResult_t CAUpdateCharacteristicsToGattClient(const char* address, const char *charValue,
const uint32_t charValueLen)
{
+ CAResult_t result = CA_SEND_FAILED;
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);
+ result = CALEServerSendUnicastMessage(address, charValue, charValueLen);
}
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+ return result;
}
CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
- const uint32_t charValueLen)
+ uint32_t charValueLen)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL(charValue, TAG, "device is null");
OIC_LOG(DEBUG, TAG, "CALEServerSendMulticastMessage");
- CALEServerSendMulticastMessage(charValue, charValueLen);
+ CAResult_t result = CALEServerSendMulticastMessage(charValue, charValueLen);
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+ return result;
}
-void CASetBleServerThreadPoolHandle(ca_thread_pool_t handle)
+void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "IN");
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
CAResult_t CALEServerStartGattServer(JNIEnv *env, jobject gattServerCallback);
/**
+ * @brief close gatt server
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGattServer [IN] Gatt Server object
+ * @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerGattClose(JNIEnv *env, jobject bluetoothGattServer);
+/**
* @brief send data
* @param env [IN] JNI interface pointer
* @param bluetoothDevice [IN] bluetooth device object
#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_SERVICE_UUID[] = "ADE3D529-C784-4F63-A987-EB69F70EE816";
+static const char OIC_GATT_CHARACTERISTIC_REQUEST_UUID[] = "AD7B334F-4637-4B86-90B6-9D787F03D218";
+static const char OIC_GATT_CHARACTERISTIC_RESPONSE_UUID[] = "E9241982-4580-42C4-8831-95048216B256";
static const char OIC_GATT_CHARACTERISTIC_CONFIG_UUID[] = "00002902-0000-1000-8000-00805f9b34fb";
static const uint32_t GATT_SUCCESS = 0;
--- /dev/null
+#######################################################
+# Build BLE adapter for Arduino
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'arduino') ])
+
+src_files = [ 'cableserver.cpp',
+ 'cablenwmonitor.cpp',
+ 'cableclient.cpp']
+
+Return('src_files')
--- /dev/null
+/******************************************************************
+*
+* 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.h"
+
+#define TAG "LEC"
+
+void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
+void CASetLEReqRespClientCallback(CABLEClientDataReceivedCallback callback)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAStartLEGattClient()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+void CAStopLEGattClient()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CATerminateLEGattClient()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
//logger.h included first to avoid conflict with RBL library PROGMEM attribute
#include "logger.h"
-#include "caleinterface_singlethread.h"
+#include "caleinterface.h"
#include <Arduino.h>
#include <SPI.h>
#include <boards.h>
#include <RBL_nRF8001.h>
-#include "caleadapter_singlethread.h"
+#include "caleadapter.h"
#include "caadapterutils.h"
#include "oic_malloc.h"
*/
static unsigned char *g_leAddress = NULL;
-CAResult_t CALEInitializeNetworkMonitor()
+CAResult_t CAInitializeLENetworkMonitor()
{
OIC_LOG(DEBUG, TAG, "IN");
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
-void CALETerminateNetworkMonitor()
+void CATerminateLENetworkMonitor()
{
OIC_LOG(DEBUG, TAG, "IN");
OIC_LOG(DEBUG, TAG, "OUT");
}
+CAResult_t CAInitializeLEAdapter()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
CAResult_t CAGetLEAdapterState()
{
OIC_LOG(DEBUG, TAG, "IN");
#include <boards.h>
#include <RBL_nRF8001.h>
-#include "caleinterface_singlethread.h"
+#include "caleinterface.h"
#include "oic_malloc.h"
#include "caadapterutils.h"
+#include "cafragmentation.h"
#define TAG "LES"
-CAResult_t CAInitializeBle()
+/**
+ * @var g_bleServerDataReceivedCallback
+ * @brief Maintains the callback to be notified on receival of network packets from other
+ * BLE devices
+ */
+static CABLEServerDataReceivedCallback g_bleServerDataReceivedCallback = NULL;
+
+/**
+ * @def MAX_EVENT_COUNT
+ * @brief Maximum number of tries to get the event on BLE Shield address.
+ */
+#define MAX_EVENT_COUNT 20
+
+static bool g_serverRunning = false;
+static char *g_coapBuffer = NULL;
+
+/**
+ * @var g_receivedDataLen
+ * @brief Actual length of data received.
+ */
+static uint32_t g_receivedDataLen = 0;
+
+/**
+ * @var g_packetDataLen
+ * @brief Total Length of data that is being fragmented.
+ */
+static uint32_t g_packetDataLen = 0;
+
+void CACheckLEDataInternal()
+{
+ CALEDoEvents();
+
+ if (CAIsLEDataAvailable())
+ {
+ // Allocate Memory for COAP Buffer and do ParseHeader
+ if (NULL == g_coapBuffer)
+ {
+ OIC_LOG(DEBUG, TAG, "IN");
+ char headerArray[CA_HEADER_LENGTH] = "";
+ while (CAIsLEDataAvailable() && g_receivedDataLen < CA_HEADER_LENGTH)
+ {
+ headerArray[g_receivedDataLen++] = CALEReadData();
+ }
+
+ 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_receivedDataLen = 0;
+ }
+
+ OIC_LOG(DEBUG, TAG, "IN");
+ while (CAIsLEDataAvailable())
+ {
+ OIC_LOG(DEBUG, TAG, "In While loop");
+ g_coapBuffer[g_receivedDataLen++] = CALEReadData();
+ if (g_receivedDataLen == g_packetDataLen)
+ {
+ OIC_LOG(DEBUG, TAG, "Read Comp BLE Pckt");
+ g_coapBuffer[g_receivedDataLen] = '\0';
+ if (g_receivedDataLen > 0)
+ {
+ OIC_LOG_V(DEBUG, TAG, "recv dataLen=%d", g_receivedDataLen);
+ //CANotifyCallback((void *)g_coapBuffer, g_dataLen, "", 0);
+ uint32_t sentLength = 0;
+ g_bleServerDataReceivedCallback("", "", g_coapBuffer,
+ g_receivedDataLen, &sentLength);
+ }
+ g_receivedDataLen = 0;
+ OICFree(g_coapBuffer);
+ g_coapBuffer = NULL;
+ break;
+ }
+ }
+ OIC_LOG(DEBUG, TAG, "OUT");
+ }
+ else
+ {
+ OIC_LOG(DEBUG, TAG, "NoData");
+ }
+ return;
+}
+
+CAResult_t CALEInitialize()
{
OIC_LOG(DEBUG, TAG, "IN");
return CA_STATUS_OK;
}
-CAResult_t CATerminateBle()
+void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "IN");
- ble_radio_reset();
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+}
+void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ OIC_LOG(DEBUG, TAG, "OUT");
}
-unsigned char CAIsBleDataAvailable()
+unsigned char CAIsLEDataAvailable()
{
return ble_available();
}
-unsigned char CAIsBleConnected()
+unsigned char CAIsLEConnected()
{
return ble_connected();
}
-char CAReadBleData()
+char CALEReadData()
{
return (char)ble_read();
}
-CAResult_t CABleDoEvents()
+CAResult_t CALEDoEvents()
{
ble_do_events();
return CA_STATUS_OK;
}
CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *char_value,
- uint8_t valueLength)
+ uint32_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.
return CA_STATUS_OK;
}
+void CASetLEReqRespServerCallback(CABLEServerDataReceivedCallback callback)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ g_bleServerDataReceivedCallback = callback;
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
+CAResult_t CAStartLEGattServer()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ CAResult_t result = CALEInitialize();
+ 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++)
+ {
+ CACheckLEDataInternal();
+ }
+
+ g_serverRunning = true;
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAStopLEGattServer()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ // There is no server running to stop.
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+void CATerminateLEGattServer()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ ble_radio_reset();
+ g_serverRunning = false;
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return;
+}
+
+void CACheckLEData()
+{
+ if (false == g_serverRunning)
+ {
+ OIC_LOG(ERROR, TAG, "Server is not running");
+ return;
+ }
+ CACheckLEDataInternal();
+}
* @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);
+CAResult_t CALEInitialize();
/**
* @brief API to check whether data is available in BLE shield
* @return - Received buffer length
*/
-unsigned char CAIsBleDataAvailable();
+unsigned char CAIsLEDataAvailable();
/**
* @brief API to check whether client is connected with BLE Shield
* @return - Connection state
*/
-unsigned char CAIsBleConnected();
+unsigned char CAIsLEConnected();
/**
* @brief API to read data from BLE shield
* @return - Data read
*/
-char CAReadBleData();
+char CALEReadData();
/**
* @brief API to perform BLE events
* @return #CA_STATUS_OK or Appropriate error code
*/
-CAResult_t CABleDoEvents();
+CAResult_t CALEDoEvents();
#ifdef __cplusplus
} /* extern "C" */
#include "cacommon.h"
#include "camutex.h"
#include "caadapterutils.h"
+#ifndef SINGLE_THREAD
#include "caqueueingthread.h"
-#include "camsgparser.h"
+#endif
+#include "cafragmentation.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "caremotehandler.h"
/**
* @var CALEADAPTER_TAG
* @brief Logging tag for module name.
*/
-#define CALEADAPTER_TAG "CA_BLE_ADAPTER"
+#define CALEADAPTER_TAG "LAD"
/**
* @var g_networkCallback
/**
* @var g_localBLEAddress
- * @brief bleAddress of the local adapter. Value will be initialized to zero, and will be updated later.
+ * @brief bleAddress of the local adapter. Value will be initialized to zero, and will
+ * be updated later.
*/
-static char g_localBLEAddress[16] = {0};
+static char g_localBLEAddress[18] = {0};
/**
* @var g_isServer
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_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
static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
/**
+ * @var g_errorHandler
+ * @brief Callback to notify error from the BLE adapter
+ */
+static CAErrorHandleCallback g_errorHandler = NULL;
+
+/**
+ * @var g_bleAdapterState
+ * @brief Storing Adapter state information
+ */
+static CAAdapterState_t g_bleAdapterState = CA_ADAPTER_DISABLED;
+
+/**
* @ENUM CALeServerStatus
* @brief status of BLE Server Status
* This ENUM provides information of LE Adapter Server status
* @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.
+* @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);
+void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
/**
* @fn CALEDeviceStateChangedCb
* @retval CA_STATUS_FAILED Operation failed
*
*/
-CAResult_t CAInitBleAdapterMutex();
+CAResult_t CAInitLEAdapterMutex();
/**
* @fn CATerminateBleAdapterMutex
*
* @return void
*/
-void CATerminateBleAdapterMutex();
+void CATerminateLEAdapterMutex();
+
+/**
+* @fn CALEErrorHandler
+* @brief prepares and notify error through error callback
+*
+* @return void
+*/
+static void CALEErrorHandler(const char *remoteAddress, const void *data, uint32_t dataLen,
+ CAResult_t result);
+
+#ifndef SINGLE_THREAD
+/**
+ * @var g_dataReceiverHandlerState
+ * @brief Stop condition of recvhandler.
+ */
+static bool g_dataReceiverHandlerState = false;
+
+/**
+ * @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_bleServerSendQueueHandle
+ * @brief Queue to process the outgoing packets from GATTServer.
+ */
+static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
+
+/**
+ * @var g_bleServerReceiverQueue
+ * @brief Queue to process the incoming packets to GATTServer
+ */
+static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
/**
* @fn CALEDataDestroyer
*/
static void CALEDataDestroyer(void *data, uint32_t size);
-CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
- CANetworkPacketReceivedCallback reqRespCallback,
- CANetworkChangeCallback netCallback,
- ca_thread_pool_t handle)
+void CAInitLEQueues()
{
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");
-
- CAResult_t result = CAInitBleAdapterMutex();
+ CAResult_t result = CAInitLEServerQueues();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerQueues failed");
+ return;
}
- result = CAInitializeLENetworkMonitor();
+ result = CAInitLEClientQueues();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
+ return;
}
- 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.startDiscoveryServer = CAStartLEDiscoveryServer;
- connHandler.sendData = CASendLEUnicastData;
- connHandler.sendDataToAll = CASendLEMulticastData;
- connHandler.GetnetInfo = CAGetLEInterfaceInformation;
- connHandler.readData = CAReadLEData;
- connHandler.terminate = CATerminateLE;
- registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
-
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-
- return CA_STATUS_OK;
-}
-
-CAResult_t CAStartLE()
-{
- 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;
}
-CAResult_t CAStopLE()
+CAResult_t CAInitLEServerQueues()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CAStopBleQueues();
+ ca_mutex_lock(g_bleAdapterThreadPoolMutex);
- ca_mutex_lock(g_bleIsServerMutex);
- if (true == g_isServer)
+ CAResult_t result = CAInitLEServerSenderQueue();
+ if (CA_STATUS_OK != result)
{
- CAStopBleGattServer();
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
+ ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+ return CA_STATUS_FAILED;
}
- else
+
+ result = CAInitLEServerReceiverQueue();
+ if (CA_STATUS_OK != result)
{
- CAStopBLEGattClient();
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
+ ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+ return CA_STATUS_FAILED;
}
- ca_mutex_unlock(g_bleIsServerMutex);
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ g_dataReceiverHandlerState = true;
+
+ ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
-void CATerminateLE()
+CAResult_t CAInitLEClientQueues()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CASetBLEReqRespServerCallback(NULL);
- CASetBLEReqRespClientCallback(NULL);
- CALERegisterNetworkNotifications(NULL);
- CASetBLEReqRespAdapterCallback(NULL);
- CATerminateLENetworkMonitor();
+ ca_mutex_lock(g_bleAdapterThreadPoolMutex);
- ca_mutex_lock(g_bleIsServerMutex);
- if (true == g_isServer)
+ CAResult_t result = CAInitLEClientSenderQueue();
+ if (CA_STATUS_OK != result)
{
- CATerminateBleGattServer();
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
+ ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+ return CA_STATUS_FAILED;
}
- else
+
+ result = CAInitLEClientReceiverQueue();
+ if (CA_STATUS_OK != result)
{
- CATerminateBLEGattClient();
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
+ ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+ return CA_STATUS_FAILED;
}
- ca_mutex_unlock(g_bleIsServerMutex);
- CATerminateBleQueues();
+ g_dataReceiverHandlerState = true;
- CATerminateBleAdapterMutex();
+ ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return CA_STATUS_OK;
}
-CAResult_t CAStartLEListeningServer()
+CAResult_t CAInitLEServerSenderQueue()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
-
- CAResult_t result = CAInitBleServerQueues();
- if (CA_STATUS_OK != result)
+ // Check if the message queue is already initialized
+ if (g_bleServerSendQueueHandle)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
- return CA_STATUS_FAILED;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
+ return CA_STATUS_OK;
}
- result = CAGetLEAdapterState();
- if (CA_ADAPTER_NOT_ENABLED == result)
+ // Create send message queue
+ g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_bleServerSendQueueHandle)
{
- gLeServerStatus = CA_LISTENING_SERVER;
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
- return CA_STATUS_OK;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+ return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_FAILED == result)
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
+ g_bleAdapterThreadPool,
+ CALEServerSendDataThread, CALEDataDestroyer))
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
+ OICFree(g_bleServerSendQueueHandle);
+ g_bleServerSendQueueHandle = NULL;
return CA_STATUS_FAILED;
}
- CAStartBleGattServer();
-
- ca_mutex_lock(g_bleIsServerMutex);
- g_isServer = true;
- ca_mutex_unlock(g_bleIsServerMutex);
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerSendQueueHandle))
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
+ OICFree(g_bleServerSendQueueHandle);
+ g_bleServerSendQueueHandle = NULL;
+ return CA_STATUS_FAILED;
+ }
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
-CAResult_t CAStartLEDiscoveryServer()
+CAResult_t CAInitLEClientSenderQueue()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CAResult_t result = CAInitBleClientQueues();
- if (CA_STATUS_OK != result)
+ if (g_bleClientSendQueueHandle)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
- return CA_STATUS_FAILED;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
+ return CA_STATUS_OK;
}
- result = CAGetLEAdapterState();
- if (CA_ADAPTER_NOT_ENABLED == result)
+ // Create send message queue
+ g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_bleClientSendQueueHandle)
{
- gLeServerStatus = CA_DISCOVERY_SERVER;
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
- return CA_STATUS_OK;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+ return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_FAILED == result)
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
+ g_bleAdapterThreadPool,
+ CALEClientSendDataThread, CALEDataDestroyer))
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
+ OICFree(g_bleClientSendQueueHandle);
+ g_bleClientSendQueueHandle = NULL;
return CA_STATUS_FAILED;
}
- CAStartBLEGattClient();
-
- ca_mutex_lock(g_bleIsServerMutex);
- g_isServer = false;
- ca_mutex_unlock(g_bleIsServerMutex);
+ 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;
}
-CAResult_t CAStartLENotifyServer()
+CAResult_t CAInitLEServerReceiverQueue()
{
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;
+ }
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return CA_STATUS_OK;
-}
-
-uint32_t CASendLENotification(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+ // 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_bleServerSendQueueHandle);
+ return CA_MEMORY_ALLOC_FAILED;
+ }
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return 0;
-}
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue, g_bleAdapterThreadPool,
+ CALEServerDataReceiverHandler, CALEDataDestroyer))
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
+ OICFree(g_bleServerReceiverQueue);
+ g_bleServerReceiverQueue = NULL;
+ return CA_STATUS_FAILED;
+ }
-CAResult_t CAReadLEData()
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+ 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;
+ }
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
-int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
+CAResult_t CAInitLEClientReceiverQueue()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- //Input validation
- 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;
-
- ca_mutex_lock(g_bleIsServerMutex);
- if (true == g_isServer)
+ // Check if the message queue is already initialized
+ if (g_bleClientReceiverQueue)
{
- result = CABLEServerSendData(endpoint, data, dataLen);
- if (CA_STATUS_OK != result)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG,
- "[SendLEUnicastData] CABleServerSenderQueueEnqueueMessage failed \n");
- ca_mutex_unlock(g_bleIsServerMutex);
- return -1;
- }
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
}
else
{
- result = CABLEClientSendData(endpoint, data, dataLen);
- if (CA_STATUS_OK != result)
+ // Create send message queue
+ g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_bleClientReceiverQueue)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG,
- "[SendLEUnicastData] CABleClientSenderQueueEnqueueMessage failed \n");
- ca_mutex_unlock(g_bleIsServerMutex);
- return -1;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+ OICFree(g_bleClientSendQueueHandle);
+ return CA_MEMORY_ALLOC_FAILED;
}
- }
- ca_mutex_unlock(g_bleIsServerMutex);
-
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return dataLen;
-}
-
-int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
-
- //Input validation
- VERIFY_NON_NULL_RET(data, NULL, "Data is null", -1);
-
- if (0 >= dataLen)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
- return -1;
- }
- CAResult_t result = CA_STATUS_FAILED;
-
- ca_mutex_lock(g_bleIsServerMutex);
- if (true == g_isServer)
- {
- result = CABLEServerSendData(NULL, data, dataLen);
- if (CA_STATUS_OK != result)
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
+ g_bleAdapterThreadPool,
+ CALEClientDataReceiverHandler, NULL))
{
- OIC_LOG(ERROR, CALEADAPTER_TAG,
- "[SendLEMulticastDataToAll] CABleServerSenderQueueEnqueueMessage failed" );
- ca_mutex_unlock(g_bleIsServerMutex);
- return -1;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
+ OICFree(g_bleClientSendQueueHandle);
+ OICFree(g_bleClientReceiverQueue);
+ g_bleClientReceiverQueue = NULL;
+ return CA_STATUS_FAILED;
}
}
- else
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
{
- result = CABLEClientSendData(NULL, data, dataLen);
- if (CA_STATUS_OK != result)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG,
- "[SendLEMulticastDataToAll] CABleClientSenderQueueEnqueueMessage failed" );
- ca_mutex_unlock(g_bleIsServerMutex);
- return -1;
- }
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
+ OICFree(g_bleClientReceiverQueue);
+ g_bleClientReceiverQueue = NULL;
+ return CA_STATUS_FAILED;
}
- ca_mutex_unlock(g_bleIsServerMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return dataLen;
+ return CA_STATUS_OK;
}
-CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
+void CAStopLEQueues()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- VERIFY_NON_NULL(info, NULL, "CALocalConnectivity info is null");
-
- char *local_address = NULL;
-
- CAResult_t res = CAGetLEAddress(&local_address);
- if (CA_STATUS_OK != res)
+ ca_mutex_lock(g_bleClientSendDataMutex);
+ if (NULL != g_bleClientSendQueueHandle)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
- return res;
+ CAQueueingThreadStop(g_bleClientSendQueueHandle);
}
+ ca_mutex_unlock(g_bleClientSendDataMutex);
- if (NULL == local_address)
+ ca_mutex_lock(g_bleClientReceiveDataMutex);
+ if (NULL != g_bleClientReceiverQueue)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
- return CA_STATUS_FAILED;
+ CAQueueingThreadStop(g_bleClientReceiverQueue);
}
+ ca_mutex_unlock(g_bleClientReceiveDataMutex);
- *size = 0;
- (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof (CAEndpoint_t));
- if (NULL == (*info))
+ ca_mutex_lock(g_bleServerSendDataMutex);
+ if (NULL != g_bleServerSendQueueHandle)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
- OICFree(local_address);
- return CA_STATUS_FAILED;
+ CAQueueingThreadStop(g_bleServerSendQueueHandle);
}
+ ca_mutex_unlock(g_bleServerSendDataMutex);
- size_t local_address_len = strlen(local_address);
-
- if(local_address_len >= sizeof(g_localBLEAddress) ||
- local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
+ ca_mutex_lock(g_bleServerReceiveDataMutex);
+ if (NULL != g_bleServerReceiverQueue)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
- OICFree(*info);
- OICFree(local_address);
- return CA_STATUS_FAILED;
+ CAQueueingThreadStop(g_bleServerReceiverQueue);
}
-
- OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
- ca_mutex_lock(g_bleLocalAddressMutex);
- OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
- ca_mutex_unlock(g_bleLocalAddressMutex);
-
- (*info)->adapter = CA_ADAPTER_GATT_BTLE;
- *size = 1;
- OICFree(local_address);
+ ca_mutex_unlock(g_bleServerReceiveDataMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return CA_STATUS_OK;
}
-CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
+void CATerminateLEQueues()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- ca_mutex_lock(g_bleNetworkCbMutex);
- g_networkCallback = netCallback;
- ca_mutex_unlock(g_bleNetworkCbMutex);
- CAResult_t res = CA_STATUS_OK;
- if (netCallback)
- {
- res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
- if (CA_STATUS_OK != res)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
- }
- }
- else
- {
- res = CAUnSetLEAdapterStateChangedCb();
- if (CA_STATUS_OK != res)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
- }
- }
+ CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
+ OICFree(g_bleClientSendQueueHandle);
+ g_bleClientSendQueueHandle = NULL;
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return res;
-}
-void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+ CAQueueingThreadDestroy(g_bleClientReceiverQueue);
+ OICFree(g_bleClientReceiverQueue);
+ g_bleClientReceiverQueue = NULL;
- VERIFY_NON_NULL_VOID(g_localBLEAddress, NULL, "g_localBLEAddress is null");
- CAEndpoint_t localEndpoint = {};
- localEndpoint.adapter = CA_ADAPTER_GATT_BTLE;
- ca_mutex_lock(g_bleLocalAddressMutex);
- OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), 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;
+ CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
+ OICFree(g_bleServerSendQueueHandle);
+ g_bleServerSendQueueHandle = NULL;
- 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);
+
+ CAQueueingThreadDestroy(g_bleServerReceiverQueue);
+ OICFree(g_bleServerReceiverQueue);
+ g_bleServerReceiverQueue = NULL;
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
-CAResult_t CAInitBleAdapterMutex()
+void CALEServerDataReceiverHandler(void *threadData)
{
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;
- }
- }
+ static uint32_t recvDataLen = 0;
+ static uint32_t totalDataLen = 0;
+ static char *defragData = NULL;
+ static bool isHeaderAvailable = false;
+ static CAEndpoint_t *remoteEndpoint = NULL;
- 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;
- }
- }
+ ca_mutex_lock(g_bleServerReceiveDataMutex);
- if (NULL == g_bleAdapterThreadPoolMutex)
+ if (g_dataReceiverHandlerState)
{
- g_bleAdapterThreadPoolMutex = ca_mutex_new();
- if (NULL == g_bleAdapterThreadPoolMutex)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
- return CA_STATUS_FAILED;
- }
- }
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
- if (NULL == g_bleClientSendDataMutex)
- {
- g_bleClientSendDataMutex = ca_mutex_new();
- if (NULL == g_bleClientSendDataMutex)
+ CALEData_t *bleData = (CALEData_t *) threadData;
+ if (!bleData)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
- return CA_STATUS_FAILED;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
+ return;
}
- }
- 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;
- }
- }
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
- if (NULL == g_bleServerSendDataMutex)
- {
- g_bleServerSendDataMutex = ca_mutex_new();
- if (NULL == g_bleServerSendDataMutex)
+ if (!isHeaderAvailable)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
- return CA_STATUS_FAILED;
- }
- }
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
+ totalDataLen = CAParseHeader((char*)bleData->data);
- if (NULL == g_bleServerReceiveDataMutex)
- {
- g_bleServerReceiveDataMutex = ca_mutex_new();
- if (NULL == g_bleServerReceiveDataMutex)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
- return CA_STATUS_FAILED;
- }
- }
+ 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);
- if (NULL == g_bleAdapterReqRespCbMutex)
- {
- g_bleAdapterReqRespCbMutex = ca_mutex_new();
- if (NULL == g_bleAdapterReqRespCbMutex)
+ defragData = (char *) OICCalloc(totalDataLen + 1, sizeof(char));
+ if (NULL == defragData)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
+ return;
+ }
+
+ const char *remoteAddress = bleData->remoteEndpoint->addr;
+
+ remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_GATT_BTLE,
+ remoteAddress, 0);
+
+ memcpy(defragData + recvDataLen, bleData->data + CA_HEADER_LENGTH,
+ bleData->dataLen - CA_HEADER_LENGTH);
+ recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
+ isHeaderAvailable = true;
+ }
+ else
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
- return CA_STATUS_FAILED;
+ 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);
}
- }
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- return CA_STATUS_OK;
+ if (false == g_dataReceiverHandlerState)
+ {
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
+ recvDataLen = 0;
+ totalDataLen = 0;
+ isHeaderAvailable = false;
+ OICFree(defragData);
+ CAFreeEndpoint(remoteEndpoint);
+ ca_mutex_unlock(g_bleServerReceiveDataMutex);
+ return;
+ }
+ }
+ ca_mutex_unlock(g_bleServerReceiveDataMutex);
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
-void CATerminateBleAdapterMutex()
+void CALEClientDataReceiverHandler(void *threadData)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- ca_mutex_free(g_bleIsServerMutex);
- g_bleIsServerMutex = NULL;
-
- ca_mutex_free(g_bleNetworkCbMutex);
- g_bleNetworkCbMutex = NULL;
+ static const char *remoteAddress = NULL;
+ static uint32_t recvDataLen = 0;
+ static uint32_t totalDataLen = 0;
+ static char *defragData = NULL;
+ static bool isHeaderAvailable = false;
+ static CAEndpoint_t *remoteEndpoint = NULL;
- ca_mutex_free(g_bleLocalAddressMutex);
- g_bleLocalAddressMutex = NULL;
+ ca_mutex_lock(g_bleClientReceiveDataMutex);
- ca_mutex_free(g_bleAdapterThreadPoolMutex);
- g_bleAdapterThreadPoolMutex = NULL;
+ if (g_dataReceiverHandlerState)
+ {
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
- ca_mutex_free(g_bleClientSendDataMutex);
- g_bleClientSendDataMutex = NULL;
+ CALEData_t *bleData = (CALEData_t *) threadData;
+ if (!bleData)
+ {
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
+ return;
+ }
- ca_mutex_free(g_bleClientReceiveDataMutex);
- g_bleClientReceiveDataMutex = NULL;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
- ca_mutex_free(g_bleServerSendDataMutex);
- g_bleServerSendDataMutex = NULL;
+ if (!isHeaderAvailable)
+ {
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
- ca_mutex_free(g_bleServerReceiveDataMutex);
- g_bleServerReceiveDataMutex = NULL;
+ 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);
- ca_mutex_free(g_bleAdapterReqRespCbMutex);
- g_bleAdapterReqRespCbMutex = NULL;
+ defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
+ if (NULL == defragData)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
+ return;
+ }
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-}
+ remoteAddress = bleData->remoteEndpoint->addr;
-void CAInitBleQueues()
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+ remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_GATT_BTLE,
+ remoteAddress, 0);
- CAResult_t result = CAInitBleServerQueues();
- if (CA_STATUS_OK != result)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerQueues failed");
- return;
- }
+ 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);
+ }
- result = CAInitBleClientQueues();
- if (CA_STATUS_OK != result)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
- return;
+ if (false == g_dataReceiverHandlerState)
+ {
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
+ OICFree(defragData);
+ CAFreeEndpoint(remoteEndpoint);
+ ca_mutex_unlock(g_bleClientReceiveDataMutex);
+ return;
+ }
}
-
+ ca_mutex_unlock(g_bleClientReceiveDataMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
-CAResult_t CAInitBleServerQueues()
+void CALEServerSendDataThread(void *threadData)
{
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)
+ CALEData_t *bleData = (CALEData_t *) threadData;
+ if (!bleData)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
- ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
- return CA_STATUS_FAILED;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
+ return;
}
- 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");
+ char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
+ VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
- ca_mutex_lock(g_bleAdapterThreadPoolMutex);
+ int32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
- CAResult_t result = CAInitBleClientSenderQueue();
- if (CA_STATUS_OK != result)
+ 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, "CAInitBleClientSenderQueue failed");
- ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
+ OICFree(header);
+ return;
}
- result = CAInitBleClientReceiverQueue();
- if (CA_STATUS_OK != result)
+ CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
+ if (CA_STATUS_OK != result )
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
- ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
+ OICFree(header);
+ OICFree(dataSegment);
+ return ;
}
- g_dataReceiverHandlerState = true;
-
- ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
-
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return CA_STATUS_OK;
-}
+ memcpy(dataSegment, header, CA_HEADER_LENGTH);
+ OICFree(header);
-CAResult_t CAInitBleServerSenderQueue()
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- // Check if the message queue is already initialized
- if (g_sendQueueHandle)
+ int32_t length = 0;
+ if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
- return CA_STATUS_OK;
+ length = totalLength;
+ memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
}
-
- // Create send message queue
- g_sendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
- if (!g_sendQueueHandle)
+ else
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
- return CA_MEMORY_ALLOC_FAILED;
+ length = CA_SUPPORTED_BLE_MTU_SIZE;
+ memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
+ CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_bleAdapterThreadPool,
- CABLEServerSendDataThread, CALEDataDestroyer))
+ 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(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(g_sendQueueHandle);
- g_sendQueueHandle = NULL;
- return CA_STATUS_FAILED;
- }
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
+ result = CAUpdateCharacteristicsToGattClient(
+ bleData->remoteEndpoint->addr, dataSegment, length);
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+ g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return;
+ }
- if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
+ 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->addr,
+ 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);
+ g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, 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->addr,
+ 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);
+ g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return;
+ }
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
+ }
+ }
+ else
{
- 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, "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);
+ CALEErrorHandler(NULL, bleData->data, bleData->dataLen, 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);
+ CALEErrorHandler(NULL, bleData->data, bleData->dataLen, 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);
+ CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return;
+ }
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
+ }
}
+ OICFree(dataSegment);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return CA_STATUS_OK;
}
-CAResult_t CAInitBleClientSenderQueue()
+void CALEClientSendDataThread(void *threadData)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- if (g_bleClientSendQueueHandle)
+ CALEData_t *bleData = (CALEData_t *) threadData;
+ if (!bleData)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
- return CA_STATUS_OK;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
+ return;
}
- // 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;
- }
+ char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
+ VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
- if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle, g_bleAdapterThreadPool,
- CABLEClientSendDataThread, CALEDataDestroyer))
+ uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
+ char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
+ if (NULL == dataSegment)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(g_bleClientSendQueueHandle);
- g_bleClientSendQueueHandle = NULL;
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
+ OICFree(header);
+ return;
}
- if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientSendQueueHandle))
+ CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
+ if (CA_STATUS_OK != result )
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
- OICFree(g_bleClientSendQueueHandle);
- g_bleClientSendQueueHandle = NULL;
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
+ OICFree(header);
+ OICFree(dataSegment);
+ return ;
}
+ memcpy(dataSegment, header, CA_HEADER_LENGTH);
+ OICFree(header);
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return CA_STATUS_OK;
-}
-
-CAResult_t CAInitBleServerReceiverQueue()
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- // Check if the message queue is already initialized
- if (g_bleServerReceiverQueue)
+ uint32_t length = 0;
+ if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
- return CA_STATUS_OK;
+ length = totalLength;
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
+ memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
}
-
- // Create send message queue
- g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
- if (!g_bleServerReceiverQueue)
+ else
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
- OICFree(g_sendQueueHandle);
- return CA_MEMORY_ALLOC_FAILED;
+ 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);
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue, g_bleAdapterThreadPool,
- CABLEServerDataReceiverHandler, CALEDataDestroyer))
+ uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
+ uint32_t index = 0;
+ if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(g_bleServerReceiverQueue);
- g_bleServerReceiverQueue = NULL;
- return CA_STATUS_FAILED;
- }
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
+ // Send the first segment with the header.
+ result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addr,
+ dataSegment,
+ length,
+ LE_UNICAST, 0);
- 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;
- }
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+ g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return ;
+ }
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return CA_STATUS_OK;
-}
+ 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->addr,
+ 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);
+ g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return;
+ }
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]",
+ CA_SUPPORTED_BLE_MTU_SIZE);
+ }
-CAResult_t CAInitBleClientReceiverQueue()
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+ 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->addr,
+ bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+ remainingLen,
+ LE_UNICAST, 0);
- // Check if the message queue is already initialized
- if (g_bleClientReceiverQueue)
- {
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+ result);
+ g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return;
+ }
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]", remainingLen);
+ }
}
else
{
- // Create send message queue
- g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
- if (!g_bleClientReceiverQueue)
+ //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(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
- OICFree(g_bleClientSendQueueHandle);
- return CA_MEMORY_ALLOC_FAILED;
+ OIC_LOG_V(ERROR, CALEADAPTER_TAG,
+ "Update characteristics (all) failed, result [%d]", result);
+ CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return ;
}
-
- if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue, g_bleAdapterThreadPool,
- CABLEClientDataReceiverHandler, NULL))
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]", length);
+ // Send the remaining header.
+ for (index = 1; index < iter; index++)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(g_bleClientSendQueueHandle);
- OICFree(g_bleClientReceiverQueue);
- g_bleClientReceiverQueue = NULL;
- return CA_STATUS_FAILED;
+ 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);
+ CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return;
+ }
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]",
+ CA_SUPPORTED_BLE_MTU_SIZE);
}
- }
- 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;
-}
-void CAStopBleQueues()
-{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+ 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);
+ CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
+ OICFree(dataSegment);
+ return;
+ }
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]", remainingLen);
+ }
- 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);
+ OICFree(dataSegment);
- ca_mutex_lock(g_bleServerSendDataMutex);
- if (NULL != g_sendQueueHandle)
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
+}
+
+CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
+ uint32_t dataLength)
+{
+ CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
+ if (!bleData)
{
- CAQueueingThreadStop(g_sendQueueHandle);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+ return NULL;
}
- ca_mutex_unlock(g_bleServerSendDataMutex);
- ca_mutex_lock(g_bleServerReceiveDataMutex);
- if (NULL != g_bleServerReceiverQueue)
+ bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
+ bleData->data = (void *)OICCalloc(dataLength + 1, 1);
+ if (NULL == bleData->data)
{
- CAQueueingThreadStop(g_bleServerReceiverQueue);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+ CAFreeLEData(bleData);
+ return NULL;
}
- ca_mutex_unlock(g_bleServerReceiveDataMutex);
+ memcpy(bleData->data, data, dataLength);
+ bleData->dataLen = dataLength;
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return bleData;
}
-void CATerminateBleQueues()
+void CAFreeLEData(CALEData_t *bleData)
{
- 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;
+ VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
+ CAFreeEndpoint(bleData->remoteEndpoint);
+ OICFree(bleData->data);
+ OICFree(bleData);
+}
- CAQueueingThreadDestroy(g_bleServerReceiverQueue);
- OICFree(g_bleServerReceiverQueue);
- g_bleServerReceiverQueue = NULL;
+void CALEDataDestroyer(void *data, uint32_t size)
+{
+ CALEData_t *ledata = (CALEData_t *) data;
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ CAFreeLEData(ledata);
}
-void CABLEServerDataReceiverHandler(void *threadData)
+#endif
+
+CAResult_t CAInitLEAdapterMutex()
{
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 CAEndpoint_t *remoteEndpoint = NULL;
-
- ca_mutex_lock(g_bleServerReceiveDataMutex);
-
- if (g_dataReceiverHandlerState)
+ if (NULL == g_bleIsServerMutex)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
-
- CALEData_t *bleData = (CALEData_t *) threadData;
- if (!bleData)
+ g_bleIsServerMutex = ca_mutex_new();
+ if (NULL == g_bleIsServerMutex)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
- return;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+ return CA_STATUS_FAILED;
}
+ }
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
-
- if (!isHeaderAvailable)
+ if (NULL == g_bleNetworkCbMutex)
+ {
+ g_bleNetworkCbMutex = ca_mutex_new();
+ if (NULL == g_bleNetworkCbMutex)
{
- 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);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+ return CA_STATUS_FAILED;
+ }
+ }
- defragData = (char *) OICCalloc(totalDataLen + 1, sizeof(char));
- if (NULL == defragData)
- {
- OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
- return;
- }
+ 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;
+ }
+ }
- const char *remoteAddress = bleData->remoteEndpoint->addr;
+ 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;
+ }
+ }
- remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
+ 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;
+ }
+ }
- memcpy(defragData + recvDataLen, bleData->data + CA_HEADER_LENGTH,
- bleData->dataLen - CA_HEADER_LENGTH);
- recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
- isHeaderAvailable = true;
+ 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;
}
- else
+ }
+
+ if (NULL == g_bleServerSendDataMutex)
+ {
+ g_bleServerSendDataMutex = ca_mutex_new();
+ if (NULL == g_bleServerSendDataMutex)
{
- 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);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+ return CA_STATUS_FAILED;
}
- if (totalDataLen == recvDataLen)
+ }
+
+ if (NULL == g_bleServerReceiveDataMutex)
+ {
+ g_bleServerReceiveDataMutex = ca_mutex_new();
+ if (NULL == g_bleServerReceiveDataMutex)
{
- 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);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+ return CA_STATUS_FAILED;
}
+ }
- if (false == g_dataReceiverHandlerState)
+ if (NULL == g_bleAdapterReqRespCbMutex)
+ {
+ g_bleAdapterReqRespCbMutex = ca_mutex_new();
+ if (NULL == g_bleAdapterReqRespCbMutex)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
- recvDataLen = 0;
- totalDataLen = 0;
- isHeaderAvailable = false;
- OICFree(defragData);
- CAAdapterFreeEndpoint(remoteEndpoint);
- ca_mutex_unlock(g_bleServerReceiveDataMutex);
- return;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+ return CA_STATUS_FAILED;
}
}
- ca_mutex_unlock(g_bleServerReceiveDataMutex);
+
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return CA_STATUS_OK;
}
-void CABLEClientDataReceiverHandler(void *threadData)
+void CATerminateLEAdapterMutex()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- static const char *remoteAddress = NULL;
- static uint32_t recvDataLen = 0;
- static uint32_t totalDataLen = 0;
- static char *defragData = NULL;
- static bool isHeaderAvailable = false;
- static CAEndpoint_t *remoteEndpoint = NULL;
-
- ca_mutex_lock(g_bleClientReceiveDataMutex);
+ ca_mutex_free(g_bleIsServerMutex);
+ g_bleIsServerMutex = NULL;
- if (g_dataReceiverHandlerState)
- {
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
+ ca_mutex_free(g_bleNetworkCbMutex);
+ g_bleNetworkCbMutex = NULL;
- CALEData_t *bleData = (CALEData_t *) threadData;
- if (!bleData)
- {
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
- return;
- }
+ ca_mutex_free(g_bleLocalAddressMutex);
+ g_bleLocalAddressMutex = NULL;
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
+ ca_mutex_free(g_bleAdapterThreadPoolMutex);
+ g_bleAdapterThreadPoolMutex = NULL;
- if (!isHeaderAvailable)
- {
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
+ ca_mutex_free(g_bleClientSendDataMutex);
+ g_bleClientSendDataMutex = NULL;
- 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;
- }
+ ca_mutex_free(g_bleClientReceiveDataMutex);
+ g_bleClientReceiveDataMutex = NULL;
- remoteAddress = bleData->remoteEndpoint->addr;
+ ca_mutex_free(g_bleServerSendDataMutex);
+ g_bleServerSendDataMutex = NULL;
- remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
+ ca_mutex_free(g_bleServerReceiveDataMutex);
+ g_bleServerReceiveDataMutex = NULL;
- 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);
- }
+ ca_mutex_free(g_bleAdapterReqRespCbMutex);
+ g_bleAdapterReqRespCbMutex = NULL;
- if (false == g_dataReceiverHandlerState)
- {
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
- OICFree(defragData);
- CAAdapterFreeEndpoint(remoteEndpoint);
- ca_mutex_unlock(g_bleClientReceiveDataMutex);
- return;
- }
- }
- ca_mutex_unlock(g_bleClientReceiveDataMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
-void CABLEServerSendDataThread(void *threadData)
+CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
+ CANetworkPacketReceivedCallback reqRespCallback,
+ CANetworkChangeCallback netCallback,
+ CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CALEData_t *bleData = (CALEData_t *) threadData;
- if (!bleData)
+ //Input validation
+ VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
+ VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
+ VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
+
+ CAResult_t result = CA_STATUS_OK;
+ result = CAInitLEAdapterMutex();
+ if (CA_STATUS_OK != result)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
- return;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
+ return CA_STATUS_FAILED;
+ }
+ result = CAInitializeLENetworkMonitor();
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
+ return CA_STATUS_FAILED;
}
- char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
- VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
+ CAInitializeLEAdapter();
- int32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
+ CASetLEClientThreadPoolHandle(handle);
+ CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
+ CASetLEServerThreadPoolHandle(handle);
+ CASetLEAdapterThreadPoolHandle(handle);
+ CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
+ CASetLEReqRespAdapterCallback(reqRespCallback);
- 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;
- }
+ CASetBLEClientErrorHandleCallback(CALEErrorHandler);
+ CASetBLEServerErrorHandleCallback(CALEErrorHandler);
+ CALERegisterNetworkNotifications(netCallback);
- 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 ;
- }
+ g_errorHandler = errorCallback;
- memcpy(dataSegment, header, CA_HEADER_LENGTH);
- OICFree(header);
+ CAConnectivityHandler_t connHandler;
+ connHandler.startAdapter = CAStartLE;
+ connHandler.stopAdapter = CAStopLE;
+ connHandler.startListenServer = CAStartLEListeningServer;
+ connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
+ connHandler.sendData = CASendLEUnicastData;
+ connHandler.sendDataToAll = CASendLEMulticastData;
+ connHandler.GetnetInfo = CAGetLEInterfaceInformation;
+ connHandler.readData = CAReadLEData;
+ connHandler.terminate = CATerminateLE;
+ registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
- int32_t length = 0;
- if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAStartLE()
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE, not implemented");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAStopLE()
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+#ifndef SINGLE_THREAD
+ CAStopLEQueues();
+#endif
+
+ ca_mutex_lock(g_bleIsServerMutex);
+ if (true == g_isServer)
{
- length = totalLength;
- memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
+ CAStopLEGattServer();
}
else
{
- length = CA_SUPPORTED_BLE_MTU_SIZE;
- memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
- CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
+ CAStopLEGattClient();
}
+ ca_mutex_unlock(g_bleIsServerMutex);
- 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->addr, dataSegment, length);
- if (CA_STATUS_OK != result)
- {
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
- OICFree(dataSegment);
- return;
- }
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- 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->addr,
- 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);
- }
+ return CA_STATUS_OK;
+}
- 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->addr,
- 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);
- }
- }
+void CATerminateLE()
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+ CASetLEReqRespServerCallback(NULL);
+ CASetLEReqRespClientCallback(NULL);
+ CALERegisterNetworkNotifications(NULL);
+ CASetLEReqRespAdapterCallback(NULL);
+ CATerminateLENetworkMonitor();
+
+ ca_mutex_lock(g_bleIsServerMutex);
+ if (true == g_isServer)
+ {
+ CATerminateLEGattServer();
+ }
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);
- }
+ CATerminateLEGattClient();
}
- OICFree(dataSegment);
+ ca_mutex_unlock(g_bleIsServerMutex);
+
+#ifndef SINGLE_THREAD
+ CATerminateLEQueues();
+#endif
+ CATerminateLEAdapterMutex();
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
-void CABLEClientSendDataThread(void *threadData)
+CAResult_t CAStartLEListeningServer()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
-
- CALEData_t *bleData = (CALEData_t *) threadData;
- if (!bleData)
+ CAResult_t result = CA_STATUS_OK;
+#ifndef SINGLE_THREAD
+ result = CAInitLEServerQueues();
+ if (CA_STATUS_OK != result)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
- return;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
+ return CA_STATUS_FAILED;
}
+#endif
- 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)
+ result = CAGetLEAdapterState();
+ if (CA_ADAPTER_NOT_ENABLED == result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
- OICFree(header);
- return;
+ gLeServerStatus = CA_LISTENING_SERVER;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
+ return CA_STATUS_OK;
}
- CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
- if (CA_STATUS_OK != result )
+ if (CA_STATUS_FAILED == result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
- OICFree(header);
- OICFree(dataSegment);
- return ;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
+ return CA_STATUS_FAILED;
}
- memcpy(dataSegment, header, CA_HEADER_LENGTH);
- OICFree(header);
- uint32_t length = 0;
- if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
+ CAStartLEGattServer();
+
+ 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()
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+ CAResult_t result = CA_STATUS_OK;
+#ifndef SINGLE_THREAD
+ result = CAInitLEClientQueues();
+ if (CA_STATUS_OK != result)
{
- length = totalLength;
- OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
- memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
+ return CA_STATUS_FAILED;
}
- else
+#endif
+ result = CAGetLEAdapterState();
+ if (CA_ADAPTER_NOT_ENABLED == result)
{
- 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);
+ gLeServerStatus = CA_DISCOVERY_SERVER;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
+ return CA_STATUS_OK;
}
- uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
- uint32_t index = 0;
- if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
+ if (CA_STATUS_FAILED == result)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
- // Send the first segment with the header.
- result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addr,
- dataSegment,
- length,
- LE_UNICAST, 0);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
+ return CA_STATUS_FAILED;
+ }
- if (CA_STATUS_OK != result)
- {
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
- OICFree(dataSegment);
- return ;
- }
+ CAStartLEGattClient();
- 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->addr,
- 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);
- }
+ 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()
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+uint32_t CASendLENotification(const CAEndpoint_t *endpoint, const void *data,
+ uint32_t dataLen)
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return 0;
+}
+
+CAResult_t CAReadLEData()
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+#ifdef SINGLE_THREAD
+ CACheckLEData();
+#endif
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- 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->addr,
- bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
- remainingLen,
- LE_UNICAST, 0);
+ //Input validation
+ VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
+ VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
- if (CA_STATUS_OK != result)
+ CAResult_t result = CA_STATUS_FAILED;
+
+ ca_mutex_lock(g_bleIsServerMutex);
+ if (true == g_isServer)
+ {
+ result = CALEAdapterServerSendData(endpoint, data, dataLen);
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
+ if (g_errorHandler)
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
- result);
- OICFree(dataSegment);
- return;
+ g_errorHandler((void *) endpoint, (void *) data, dataLen, result);
}
- OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]", remainingLen);
+ ca_mutex_unlock(g_bleIsServerMutex);
+ return -1;
}
}
else
{
- //Sending Mulitcast Data
- // Send the first segment with the header.
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
- result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
+ result = CALEAdapterClientSendData(endpoint, data, dataLen);
if (CA_STATUS_OK != result)
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed (all), result [%d]", result);
- OICFree(dataSegment);
- return ;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
+ if (g_errorHandler)
+ {
+ g_errorHandler(endpoint, data, dataLen, result);
+ }
+ ca_mutex_unlock(g_bleIsServerMutex);
+ return -1;
}
- OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]", length);
- // Send the remaining header.
- for (index = 1; index < iter; index++)
+ }
+ ca_mutex_unlock(g_bleIsServerMutex);
+
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return dataLen;
+}
+
+int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+ //Input validation
+ VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
+
+ if (0 >= dataLen)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
+ return -1;
+ }
+
+ CAResult_t result = CA_STATUS_FAILED;
+
+ ca_mutex_lock(g_bleIsServerMutex);
+ if (true == g_isServer)
+ {
+ result = CALEAdapterServerSendData(NULL, data, dataLen);
+ if (CA_STATUS_OK != result)
{
- 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(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
+
+ ca_mutex_unlock(g_bleIsServerMutex);
+ if (g_errorHandler)
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]", result);
- OICFree(dataSegment);
- return;
+ g_errorHandler(endpoint, data, dataLen, result);
}
- OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]", CA_SUPPORTED_BLE_MTU_SIZE);
+ return -1;
}
-
- uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
- if ( remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
+ }
+ else
+ {
+ result = CALEAdapterClientSendData(NULL, data, dataLen);
+ if (CA_STATUS_OK != result)
{
- // 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(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
+ if (g_errorHandler)
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]", result);
- OICFree(dataSegment);
- return;
+ g_errorHandler(endpoint, data, dataLen, result);
}
- OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length is [%d]", remainingLen);
+ ca_mutex_unlock(g_bleIsServerMutex);
+ return -1;
}
-
}
+ ca_mutex_unlock(g_bleIsServerMutex);
- OICFree(dataSegment);
-
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return dataLen;
}
-CALEData_t *CACreateBLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
- uint32_t dataLength)
+CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
{
- CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
- if (!bleData)
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+ VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
+
+ char *local_address = NULL;
+
+ CAResult_t res = CAGetLEAddress(&local_address);
+ if (CA_STATUS_OK != res)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
- return NULL;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
+ return res;
}
- bleData->remoteEndpoint = CAAdapterCloneEndpoint(remoteEndpoint);
- bleData->data = (void *)OICCalloc(dataLength + 1, 1);
- if (NULL == bleData->data)
+ if (NULL == local_address)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
- CAFreeBLEData(bleData);
- return NULL;
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
+ return CA_STATUS_FAILED;
}
- memcpy(bleData->data, data, dataLength);
- bleData->dataLen = dataLength;
- return bleData;
+ *size = 0;
+ (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
+ if (NULL == (*info))
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
+ OICFree(local_address);
+ return CA_STATUS_FAILED;
+ }
+
+ size_t local_address_len = strlen(local_address);
+
+ if(local_address_len >= sizeof(g_localBLEAddress) ||
+ local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
+ OICFree(*info);
+ OICFree(local_address);
+ return CA_STATUS_FAILED;
+ }
+
+ OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
+ ca_mutex_lock(g_bleLocalAddressMutex);
+ OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
+ ca_mutex_unlock(g_bleLocalAddressMutex);
+
+ (*info)->adapter = CA_ADAPTER_GATT_BTLE;
+ *size = 1;
+ OICFree(local_address);
+
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return CA_STATUS_OK;
}
-void CAFreeBLEData(CALEData_t *bleData)
+CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
{
- VERIFY_NON_NULL_VOID(bleData, NULL, "Param bleData is NULL");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CAAdapterFreeEndpoint(bleData->remoteEndpoint);
- OICFree(bleData->data);
- OICFree(bleData);
+ ca_mutex_lock(g_bleNetworkCbMutex);
+ g_networkCallback = netCallback;
+ ca_mutex_unlock(g_bleNetworkCbMutex);
+ CAResult_t res = CA_STATUS_OK;
+ if (netCallback)
+ {
+ res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
+ }
+ }
+ else
+ {
+ res = CAUnSetLEAdapterStateChangedCb();
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
+ }
+ }
+
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+ return res;
}
-void CALEDataDestroyer(void *data, uint32_t size)
+void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
{
- CALEData_t *ledata = (CALEData_t *) data;
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CAFreeBLEData(ledata);
-}
+ VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
+ CAEndpoint_t localEndpoint = {};
+
+ ca_mutex_lock(g_bleLocalAddressMutex);
+ OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), g_localBLEAddress);
+ ca_mutex_unlock(g_bleLocalAddressMutex);
+
+ g_bleAdapterState = adapter_state;
+ // Start a GattServer/Client if gLeServerStatus is SET
+ if (CA_LISTENING_SERVER == gLeServerStatus)
+ {
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
+ CAStartLEGattServer();
+ }
+ else if (CA_DISCOVERY_SERVER == gLeServerStatus)
+ {
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
+ CAStartLEGattClient();
+ }
+ 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 CABLEClientSendData(const CAEndpoint_t *remoteEndpoint,
- const void *data,
- uint32_t dataLen)
+CAResult_t CALEAdapterClientSendData(const CAEndpoint_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(data, CALEADAPTER_TAG, "Param data is NULL");
+#ifndef SINGLE_THREAD
VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
"g_bleClientSendQueueHandle is NULL",
CA_STATUS_FAILED);
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
- CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
+ CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
if (!bleData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
ca_mutex_lock(g_bleClientSendDataMutex);
CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
ca_mutex_unlock(g_bleClientSendDataMutex);
-
+#endif
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
-CAResult_t CABLEServerSendData(const CAEndpoint_t *remoteEndpoint,
- const void *data,
- uint32_t dataLen)
+CAResult_t CALEAdapterServerSendData(const CAEndpoint_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(data, CALEADAPTER_TAG, "Param data is NULL");
+
+#ifdef SINGLE_THREAD
+ char header[CA_HEADER_LENGTH] = {0};
+
+ CAResult_t result = CAGenerateHeader(header, dataLen);
+
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
+ return -1;
+ }
+
+ if (!CAIsLEConnected())
+ {
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
+ return -1;
+ }
+
+ result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, CALEADAPTER_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, CALEADAPTER_TAG, "Update characteristics failed");
+ return -1;
+ }
+ CALEDoEvents();
+ }
- VERIFY_NON_NULL_RET(g_sendQueueHandle, CALEADAPTER_TAG,
+ 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, CALEADAPTER_TAG, "Update characteristics failed");
+ return -1;
+ }
+ CALEDoEvents();
+ }
+#else
+ VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, 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",
+ VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, 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);
+ CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
if (!bleData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
}
// Add message to send queue
ca_mutex_lock(g_bleServerSendDataMutex);
- CAQueueingThreadAddData(g_sendQueueHandle, bleData, sizeof(CALEData_t));
+ CAQueueingThreadAddData(g_bleServerSendQueueHandle, bleData, sizeof(CALEData_t));
ca_mutex_unlock(g_bleServerSendDataMutex);
-
+#endif
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)
+CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress, const char *serviceUUID,
+ const void *data, uint32_t dataLength,
+ uint32_t *sentLength)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
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");
+
+#ifdef SINGLE_THREAD
+ if(g_networkPacketReceivedCallback)
+ {
+ CAEndpoint_t endPoint = { 0 }; // will be filled by upper layer
+ endPoint.adapter = CA_ADAPTER_GATT_BTLE;
+ g_networkPacketReceivedCallback(&endPoint, data, dataLength);
+ }
+#else
VERIFY_NON_NULL_RET(g_bleServerReceiverQueue, CALEADAPTER_TAG, "g_bleServerReceiverQueue",
CA_STATUS_FAILED);
//Add message to data queue
- CAEndpoint_t *remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
+ CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
+ CA_ADAPTER_GATT_BTLE,
+ remoteAddress, 0);
if (NULL == remoteEndpoint)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
// 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);
+ CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
if (!bleData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
- CAAdapterFreeEndpoint(remoteEndpoint);
+ CAFreeEndpoint(remoteEndpoint);
return CA_MEMORY_ALLOC_FAILED;
}
- CAAdapterFreeEndpoint(remoteEndpoint);
+ CAFreeEndpoint(remoteEndpoint);
// Add message to send queue
CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
*sentLength = dataLength;
-
+#endif
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)
+CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress, const char *serviceUUID,
+ const void *data, uint32_t dataLength,
+ uint32_t *sentLength)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
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");
+#ifndef SINGLE_THREAD
VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG, "g_bleClientReceiverQueue",
CA_STATUS_FAILED);
//Add message to data queue
- CAEndpoint_t *remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
+ CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
+ CA_ADAPTER_GATT_BTLE,
+ remoteAddress, 0);
if (NULL == remoteEndpoint)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
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);
+ CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
if (!bleData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
- CAAdapterFreeEndpoint(remoteEndpoint);
+ CAFreeEndpoint(remoteEndpoint);
return CA_MEMORY_ALLOC_FAILED;
}
- CAAdapterFreeEndpoint(remoteEndpoint);
+ CAFreeEndpoint(remoteEndpoint);
// Add message to send queue
CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
*sentLength = dataLength;
-
+#endif
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
-void CASetBleAdapterThreadPoolHandle(ca_thread_pool_t handle)
+void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
-void CASetBLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
+void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
+void CALEErrorHandler(const char *remoteAddress, const void *data, uint32_t dataLen,
+ CAResult_t result)
+{
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
+
+ VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
+ CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_GATT_BTLE,
+ remoteAddress, 0);
+ //if required, will be used to build remote end point
+ g_errorHandler(rep, data, dataLen, result);
+
+ CAFreeEndpoint(rep);
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
+}
+++ /dev/null
-/******************************************************************
-*
-* 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;
-}
-
--- /dev/null
+##########################################
+# Build BLE adapter for Linux
+##########################################
+
+Import('env')
+
+src_files = [ 'caleadapter.c']
+
+Return('src_files')
static ca_thread_pool_t g_threadPoolHandle = NULL;
CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
- CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
- ca_thread_pool_t handle)
+ CANetworkPacketReceivedCallback reqRespCallback,
+ CANetworkChangeCallback netCallback,
+ CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "CAInitializeLE");
--- /dev/null
+#######################################################
+# Build BLE adapter for Tizen
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+root_dir = os.pardir
+env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'tizen'),
+ os.path.join(root_dir, 'lib/tizen/ble/inc'),
+ os.path.join(root_dir, 'lib/tizen/ble/inc/mobile')])
+
+env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
+
+src_files = [ 'cableclient.c',
+ 'cableserver.c',
+ 'cableutil.c',
+ 'cablenwmonitor.c']
+
+Return('src_files')
#include "uarraylist.h"
#include "caqueueingthread.h"
#include "caadapterutils.h"
-#include "camsgparser.h"
+#include "cafragmentation.h"
#include "oic_string.h"
#include "oic_malloc.h"
static CABLEClientDataReceivedCallback g_bleClientDataReceivedCallback = NULL;
/**
+ * @var g_clientErrorCallback
+ * @brief callback to update the error to le adapter
+ */
+static CABLEErrorHandleCallback g_clientErrorCallback;
+
+/**
* @var g_eventLoop
* @brief gmainLoop to manage the threads to receive the callback from the platfrom.
*/
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-void CASetBleClientThreadPoolHandle(ca_thread_pool_t handle)
+void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-void CASetBLEReqRespClientCallback(CABLEClientDataReceivedCallback callback)
+void CASetLEReqRespClientCallback(CABLEClientDataReceivedCallback callback)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-CAResult_t CAStartBLEGattClient()
+
+void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
+{
+ g_clientErrorCallback = callback;
+}
+
+CAResult_t CAStartLEGattClient()
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleSetScanParameter Failed");
ca_mutex_unlock(g_bleClientStateMutex);
- CATerminateBLEGattClient();
+ CATerminateLEGattClient();
return;
}
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattSetCallbacks Failed");
ca_mutex_unlock(g_bleClientStateMutex);
- CATerminateBLEGattClient();
+ CATerminateLEGattClient();
return;
}
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_start_device_discovery Failed");
ca_mutex_unlock(g_bleClientStateMutex);
- CATerminateBLEGattClient();
+ CATerminateLEGattClient();
return;
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-void CAStopBLEGattClient()
+void CAStopLEGattClient()
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-void CATerminateBLEGattClient()
+void CATerminateLEGattClient()
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
ca_mutex_lock(g_bleClientStateMutex);
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- VERIFY_NON_NULL_RET(service, NULL, "service is NULL", CA_STATUS_FAILED);
+ VERIFY_NON_NULL_RET(service, TZ_BLE_CLIENT_TAG, "service is NULL", CA_STATUS_FAILED);
- VERIFY_NON_NULL_RET(remoteAddress, NULL, "remoteAddress is NULL", CA_STATUS_FAILED);
+ VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG, "remoteAddress is NULL", CA_STATUS_FAILED);
char *addr = OICStrdup(remoteAddress);
VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- VERIFY_NON_NULL_RET(service, NULL, "service is NULL", CA_STATUS_FAILED);
+ VERIFY_NON_NULL_RET(service, TZ_BLE_CLIENT_TAG, "service is NULL", CA_STATUS_FAILED);
int ret = bt_gatt_discover_characteristic_descriptor(service,
CABleGattDescriptorDiscoveredCb, NULL);
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- VERIFY_NON_NULL(data, NULL, "data is NULL");
+ VERIFY_NON_NULL(data, TZ_BLE_CLIENT_TAG, "data is NULL");
if (0 >= dataLen)
{
ca_mutex_lock(g_bleServiceListMutex);
if ( LE_UNICAST == type)
{
- VERIFY_NON_NULL(remoteAddress, NULL, "remoteAddress is NULL");
+ VERIFY_NON_NULL(remoteAddress, TZ_BLE_CLIENT_TAG, "remoteAddress is NULL");
ret = CAGetBLEServiceInfo(g_bLEServiceList, remoteAddress, &bleServiceInfo);
}
return CA_STATUS_FAILED;
}
- VERIFY_NON_NULL(bleServiceInfo, NULL, "bleServiceInfo is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_TAG, "bleServiceInfo is NULL");
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Updating the data of length [%d] to [%s] ", dataLen,
bleServiceInfo->bdAddress);
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- VERIFY_NON_NULL(data, NULL, "data is NULL");
+ VERIFY_NON_NULL(data, TZ_BLE_CLIENT_TAG, "data is NULL");
if (0 >= dataLen)
{
/*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);
+ CAResult_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);
+ g_clientErrorCallback(NULL, data, dataLen, ret);
+ continue;
}
}
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABleClientSenderQueueEnqueueMessage
- (const CARemoteEndpoint_t *remoteEndpoint,
+ (const CAEndpoint_t *remoteEndpoint,
const void *data, uint32_t dataLen);
/**
#include "camutex.h"
#include "caqueueingthread.h"
#include "caadapterutils.h"
-#include "camsgparser.h"
+#include "cafragmentation.h"
#include "cableutil.h"
#include "oic_string.h"
#include "oic_malloc.h"
#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.
*/
static CABLEServerDataReceivedCallback g_bleServerDataReceivedCallback = NULL;
/**
+ * @var g_serverErrorCallback
+ * @brief callback to update the error to le adapter
+ */
+static CABLEErrorHandleCallback g_serverErrorCallback;
+
+/**
* @var g_isBleGattServerStarted
* @brief Boolean variable to keep the state of the GATTServer
*/
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
}
-CAResult_t CAStartBleGattServer()
+CAResult_t CAStartLEGattServer()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Gatt Server is already running");
ca_mutex_unlock(g_bleServerStateMutex);
- CATerminateBleGattServer();
+ CATerminateLEGattServer();
return;
}
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_init_service failed");
ca_mutex_unlock(g_bleServerStateMutex);
- CATerminateBleGattServer();
+ CATerminateLEGattServer();
return;
}
sleep(5); // Sleep is must because of the platform issue.
- char *serviceUUID = CA_BLE_SERVICE_UUID;
+ char *serviceUUID = OIC_BLE_SERVICE_ID;
ret = CAAddNewBleServiceInGattServer(serviceUUID);
if (CA_STATUS_OK != ret )
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewBleServiceInGattServer failed");
ca_mutex_unlock(g_bleServerStateMutex);
- CATerminateBleGattServer();
+ CATerminateLEGattServer();
return;
}
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
ca_mutex_unlock(g_bleServerStateMutex);
- CATerminateBleGattServer();
+ CATerminateLEGattServer();
return;
}
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
ca_mutex_unlock(g_bleServerStateMutex);
- CATerminateBleGattServer();
+ CATerminateLEGattServer();
return;
}
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CARegisterBleServicewithGattServer failed");
ca_mutex_unlock(g_bleServerStateMutex);
- CATerminateBleGattServer();
+ CATerminateLEGattServer();
return;
}
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_hAdvertiser is NULL");
ca_mutex_unlock(g_bleServerStateMutex);
- CATerminateBleGattServer();
+ CATerminateLEGattServer();
return;
}
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "bt_adapter_le_start_advertising failed with ret [%d] ",
res);
ca_mutex_unlock(g_bleServerStateMutex);
- CATerminateBleGattServer();
+ CATerminateLEGattServer();
return;
}
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
}
-CAResult_t CAStopBleGattServer()
+CAResult_t CAStopLEGattServer()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
return CA_STATUS_OK;
}
-void CATerminateBleGattServer()
+void CATerminateLEGattServer()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
return CA_STATUS_OK;
}
-void CASetBleServerThreadPoolHandle(ca_thread_pool_t handle)
+void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
ca_mutex_lock(g_bleServerThreadPoolMutex);
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- VERIFY_NON_NULL(serviceUUID, NULL, "Param serviceUUID is NULL");
+ VERIFY_NON_NULL(serviceUUID, TZ_BLE_SERVER_TAG, "Param serviceUUID is NULL");
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "service uuid %s", serviceUUID);
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- VERIFY_NON_NULL(svcPath, NULL, "Param svcPath is NULL");
+ VERIFY_NON_NULL(svcPath, TZ_BLE_SERVER_TAG, "Param svcPath is NULL");
int ret = bt_gatt_remove_service(svcPath);
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- VERIFY_NON_NULL(svcPath, NULL, "Param svcPath is NULL");
+ VERIFY_NON_NULL(svcPath, TZ_BLE_SERVER_TAG, "Param svcPath is NULL");
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "svcPath:%s", svcPath);
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- VERIFY_NON_NULL(charValue, NULL, "Param charValue is NULL");
+ VERIFY_NON_NULL(charValue, TZ_BLE_SERVER_TAG, "Param charValue is NULL");
- VERIFY_NON_NULL(address, NULL, "Param address is NULL");
+ VERIFY_NON_NULL(address, TZ_BLE_SERVER_TAG, "Param address is NULL");
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Client's Unicast address for sending data [%s]", address);
return CA_STATUS_OK;
}
-CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
- const uint32_t charValueLen)
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue, uint32_t charValueLen)
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- VERIFY_NON_NULL(charValue, NULL, "Param charValue is NULL");
+ VERIFY_NON_NULL(charValue, TZ_BLE_SERVER_TAG, "Param charValue is NULL");
ca_mutex_lock(g_bleCharacteristicMutex);
return CA_STATUS_OK;
}
-void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback)
+void CASetLEReqRespServerCallback(CABLEServerDataReceivedCallback callback)
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
}
+
+void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback)
+{
+ g_serverErrorCallback = callback;
+}
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABleServerSenderQueueEnqueueMessage
- (const CARemoteEndpoint_t *remoteEndpoint, const void *data, uint32_t dataLen);
+ (const CAEndpoint_t *remoteEndpoint, const void *data, uint32_t dataLen);
/**
* @brief This is the thread which will be used for processing receiver queue.
{
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");
+ VERIFY_NON_NULL(bdAddress, TZ_BLE_CLIENT_UTIL_TAG, "Param bdAddress is NULL");
+ VERIFY_NON_NULL(service, TZ_BLE_CLIENT_UTIL_TAG, "Param service is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
*bleServiceInfo = (BLEServiceInfo *) OICCalloc(1, sizeof(BLEServiceInfo));
if (NULL == *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");
+ VERIFY_NON_NULL(characteristic, TZ_BLE_CLIENT_UTIL_TAG, "Param characteristic is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
if (BLE_GATT_READ_CHAR == type )
{
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(serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceList is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
BLEServiceList *node = (BLEServiceList *) OICCalloc(1, sizeof(BLEServiceList));
if (NULL == node)
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");
+ VERIFY_NON_NULL(serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceList is NULL");
+ VERIFY_NON_NULL(*serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param *serviceList is NULL");
+ VERIFY_NON_NULL(bdAddress, TZ_BLE_CLIENT_UTIL_TAG, "Param bdAddress is NULL");
BLEServiceList *prev = NULL;
BLEServiceList *cur = *serviceList;
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");
+ VERIFY_NON_NULL(serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceList is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
+ VERIFY_NON_NULL(bdAddress, TZ_BLE_CLIENT_UTIL_TAG, "Param bdAddress is NULL");
BLEServiceList *cur = serviceList;
{
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(serviceList, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceList is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, TZ_BLE_CLIENT_UTIL_TAG, "Param bleServiceInfo is NULL");
if (0 > position)
{
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
- VERIFY_NON_NULL(serviceUUID, NULL, "Param serviceHandle is NULL");
+ VERIFY_NON_NULL(serviceUUID, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceHandle is NULL");
if (strcasecmp(serviceUUID, OIC_BLE_SERVICE_ID) != 0)
{
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
- VERIFY_NON_NULL(serviceHandle, NULL, "Param serviceHandle is NULL");
+ VERIFY_NON_NULL(serviceHandle, TZ_BLE_CLIENT_UTIL_TAG, "Param serviceHandle is NULL");
char *uuid = NULL;
int ret = bt_gatt_get_service_uuid(serviceHandle, &uuid);
int total; /**< The total number of descriptor in a characteristic */
} stGattCharDescriptor_t;
-#define OIC_BLE_SERVICE_ID "713D0000-503E-4C75-BA94-3148F18D941E"
+#define OIC_BLE_SERVICE_ID "ADE3D529-C784-4F63-A987-EB69F70EE816"
///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"
+#define CA_BLE_READ_CHAR_UUID "E9241982-4580-42C4-8831-95048216B256"
/**
* @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"
+#define CA_BLE_WRITE_CHAR_UUID "AD7B334F-4637-4B86-90B6-9D787F03D218"
/**
* @brief Used to increment the registered service count.
CAGlobals_t caglobals;
-#define TAG PCF("CA")
+#define TAG "CA"
static bool g_isInitialized = false;
}
#endif //__WITH_DTLS__
+CAResult_t CACreateEndpoint(CATransportFlags_t flags,
+ CATransportAdapter_t adapter,
+ const char *addr,
+ uint16_t port,
+ CAEndpoint_t **object)
+{
+ if (!object)
+ {
+ OIC_LOG(ERROR, TAG, "Invalid Parameter");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
+ CAEndpoint_t *endpoint = CACreateEndpointObject(flags, adapter, addr, port);
+ if (!endpoint)
+ {
+ return CA_STATUS_FAILED;
+ }
+ *object = endpoint;
+ return CA_STATUS_OK;
+}
+
void CADestroyEndpoint(CAEndpoint_t *rep)
{
OIC_LOG(DEBUG, TAG, "CADestroyEndpoint");
- CADestroyEndpointInternal(rep);
+ CAFreeEndpoint(rep);
}
CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength)
void CADestroyToken(CAToken_t token)
{
OIC_LOG(DEBUG, TAG, "CADestroyToken");
+
CADestroyTokenInternal(token);
+
+ OIC_LOG(DEBUG, TAG, "OUT");
}
CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size)
CAResult_t CAHandleRequestResponse()
{
- OIC_LOG(DEBUG, TAG, "CAHandleRequestResponse");
-
if (!g_isInitialized)
{
OIC_LOG(ERROR, TAG, "not initialized");
+++ /dev/null
-/******************************************************************
- *
- * 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 <stdbool.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"
-
-CAGlobals_t caglobals;
-
-static bool g_isInitialized = false;
-
-CAResult_t CAInitialize()
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- if (!g_isInitialized)
- {
- CAResult_t res = CAInitializeMessageHandler();
- if (res != CA_STATUS_OK)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return res;
- }
- g_isInitialized = true;
- }
-
- return CA_STATUS_OK;
-}
-
-void CATerminate()
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- if (g_isInitialized)
- {
- CASetInterfaceCallbacks(NULL, NULL, NULL);
- CATerminateMessageHandler();
- CATerminateNetworkType();
- g_isInitialized = false;
- }
-
- OIC_LOG(DEBUG, TAG, "OUT");
-}
-
-CAResult_t CAStartListeningServer()
-{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- return CAStartListeningServerAdapters();
-}
-
-CAResult_t CAStartDiscoveryServer()
-{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- return CAStartDiscoveryServerAdapters();
-}
-
-void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
- CAErrorCallback errorHandler)
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return;
- }
-
- CASetInterfaceCallbacks(ReqHandler, RespHandler, errorHandler);
- OIC_LOG(DEBUG, TAG, "OUT");
-}
-
-void CADestroyEndpoint(CAEndpoint_t *rep)
-{
- CADestroyEndpointInternal(rep);
-}
-
-CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength)
-{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- return CAGenerateTokenInternal(token, tokenLength);
-}
-
-void CADestroyToken(CAToken_t token)
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- CADestroyTokenInternal(token);
- OIC_LOG(DEBUG, TAG, "OUT");
-}
-
-CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size)
-{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- return CAGetNetworkInformationInternal(info, size);
-}
-
-CAResult_t CASendRequest(const CAEndpoint_t *object,const CARequestInfo_t *requestInfo)
-{
- OIC_LOG(DEBUG, TAG, "CASendGetRequest");
-
- return CADetachRequestMessage(object, requestInfo);
-}
-
-CAResult_t CASendNotification(const CAEndpoint_t *object,
- const CAResponseInfo_t *responseInfo)
-{
- OIC_LOG(DEBUG, TAG, "CASendNotification");
-
- return CADetachResponseMessage(object, responseInfo);
-}
-
-CAResult_t CASendResponse(const CAEndpoint_t *object,
- const CAResponseInfo_t *responseInfo)
-{
- OIC_LOG(DEBUG, TAG, "CASendResponse");
-
- return CADetachResponseMessage(object, responseInfo);
-}
-
-CAResult_t CASelectNetwork(const uint32_t interestedNetwork)
-{
- OIC_LOG_V(DEBUG, TAG, "Selected n/W=%d", interestedNetwork);
-
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- if (!(interestedNetwork & 0xf))
- {
- OIC_LOG(ERROR, TAG, "not supported");
- return CA_NOT_SUPPORTED;
- }
- CAResult_t res = CA_STATUS_OK;
-
- if (interestedNetwork & CA_ADAPTER_IP)
- {
- res = CAAddNetworkType(CA_ADAPTER_IP);
- if (res != CA_STATUS_OK)
- {
- OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
- return res;
- }
- }
-
- if (interestedNetwork & CA_ADAPTER_RFCOMM_BTEDR)
- {
- res = CAAddNetworkType(CA_ADAPTER_RFCOMM_BTEDR);
- if (res != CA_STATUS_OK)
- {
- OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
- return res;
- }
- }
-
- if (interestedNetwork & CA_ADAPTER_GATT_BTLE)
- {
- res = CAAddNetworkType(CA_ADAPTER_GATT_BTLE);
- 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 (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- if (!(nonInterestedNetwork & 0xf))
- {
- OIC_LOG(ERROR, TAG, "not supported");
- return CA_NOT_SUPPORTED;
- }
-
- CAResult_t res = CA_STATUS_OK;
-
- if (nonInterestedNetwork & CA_ADAPTER_IP)
- {
- res = CARemoveNetworkType(CA_ADAPTER_IP);
- if (res != CA_STATUS_OK)
- {
- OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
- return res;
- }
- }
-
- if (nonInterestedNetwork & CA_ADAPTER_RFCOMM_BTEDR)
- {
- res = CARemoveNetworkType(CA_ADAPTER_RFCOMM_BTEDR);
- if (res != CA_STATUS_OK)
- {
- OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
- return res;
- }
- }
-
- if (nonInterestedNetwork & CA_ADAPTER_GATT_BTLE)
- {
- res = CARemoveNetworkType(CA_ADAPTER_GATT_BTLE);
- 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()
-{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- CAHandleRequestResponseCallbacks();
- return CA_STATUS_OK;
-}
-
#include <string.h>
#include <inttypes.h>
+#include "logger.h"
+#include "oic_malloc.h"
+#include "caadapterutils.h"
+#include "canetworkconfigurator.h"
#include "cainterfacecontroller.h"
-#include "caipadapter.h"
#include "caedradapter.h"
#include "caleadapter.h"
-#include "canetworkconfigurator.h"
#include "caremotehandler.h"
-#include "oic_malloc.h"
-#include "logger.h"
#include "cathreadpool.h"
+#include "caipadapter.h"
-#define TAG PCF("CA")
+#define TAG "CA"
#define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \
{OIC_LOG(ERROR, TAG, "memory error");goto memory_error_exit;} }
{
case CA_ADAPTER_IP:
return 0;
- case CA_ADAPTER_RFCOMM_BTEDR:
- return 1;
case CA_ADAPTER_GATT_BTLE:
+ return 1;
+ case CA_ADAPTER_RFCOMM_BTEDR:
return 2;
default:
break;
static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportAdapter_t cType)
{
- OIC_LOG(DEBUG, TAG, "CARegisterCallback - Entry");
+ OIC_LOG(DEBUG, TAG, "IN");
if(handler.startAdapter == NULL ||
handler.startListenServer == NULL ||
g_adapterHandler[index] = handler;
OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", cType);
+ OIC_LOG(DEBUG, TAG, "OUT");
}
static void CAReceivedPacketCallback(const CAEndpoint_t *endpoint, void *data, uint32_t dataLen)
{
- OIC_LOG(DEBUG, TAG, "receivedPacketCallback in interface controller");
+ OIC_LOG(DEBUG, TAG, "IN");
// Call the callback.
if (g_networkPacketReceivedCallback != NULL)
OIC_LOG(ERROR, TAG, "network packet received callback is NULL!");
}
+
+ OIC_LOG(DEBUG, TAG, "OUT");
}
static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
{
- OIC_LOG(DEBUG, TAG, "Network Changed callback");
+ OIC_LOG(DEBUG, TAG, "IN");
// Call the callback.
if (g_networkChangeCallback != NULL)
{
g_networkChangeCallback(info, status);
}
+
+ OIC_LOG(DEBUG, TAG, "OUT");
}
static void CAAdapterErrorHandleCallback(const CAEndpoint_t *endpoint,
// Initialize adapters and register callback.
#ifdef IP_ADAPTER
- CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, handle);
+ CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
+ CAAdapterErrorHandleCallback, handle);
#endif /* IP_ADAPTER */
#ifdef EDR_ADAPTER
- CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, handle);
+ CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
+ CAAdapterErrorHandleCallback, handle);
#endif /* EDR_ADAPTER */
#ifdef LE_ADAPTER
- CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, handle);
+ CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
+ CAAdapterErrorHandleCallback, handle);
#endif /* LE_ADAPTER */
}
void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback)
{
- OIC_LOG(DEBUG, TAG, "Set packet received callback");
+ OIC_LOG(DEBUG, TAG, "IN");
g_networkPacketReceivedCallback = callback;
+
+ OIC_LOG(DEBUG, TAG, "OUT");
}
void CASetNetworkChangeCallback(CANetworkChangeCallback callback)
{
- OIC_LOG(DEBUG, TAG, "Set network change callback");
+ OIC_LOG(DEBUG, TAG, "IN");
g_networkChangeCallback = callback;
+
+ OIC_LOG(DEBUG, TAG, "OUT");
}
void CASetErrorHandleCallback(CAErrorHandleCallback errorCallback)
CAResult_t CASendUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
{
- OIC_LOG(DEBUG, TAG, "Send unicast data to enabled interface..");
+ OIC_LOG(DEBUG, TAG, "IN");
CAResult_t res = CA_STATUS_FAILED;
{
res = CA_STATUS_OK;
}
+
+ OIC_LOG(DEBUG, TAG, "OUT");
return res;
}
CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
{
- OIC_LOG(DEBUG, TAG, "Send multicast data to enabled interface..");
+ OIC_LOG(DEBUG, TAG, "IN");
CAResult_t res = CA_SEND_FAILED;
u_arraylist_t *list = CAGetSelectedNetworkList();
}
}
+ OIC_LOG(DEBUG, TAG, "OUT");
+
return res;
}
CAResult_t CAStartListeningServerAdapters()
{
- OIC_LOG(DEBUG, TAG, "Start listening server from adapters..");
+ OIC_LOG(DEBUG, TAG, "IN");
u_arraylist_t *list = CAGetSelectedNetworkList();
if (!list)
}
}
+ OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAStartDiscoveryServerAdapters()
{
- OIC_LOG(DEBUG, TAG, "Start discovery server from adapters..");
+ OIC_LOG(DEBUG, TAG, "IN");
u_arraylist_t *list = CAGetSelectedNetworkList();
}
}
+ OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
void CATerminateAdapters()
{
- OIC_LOG(DEBUG, TAG, "terminate all adapters..");
+ OIC_LOG(DEBUG, TAG, "IN");
uint32_t index;
for (index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
g_adapterHandler[index].terminate();
}
}
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+#ifdef SINGLE_THREAD
+CAResult_t CAReadData()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ u_arraylist_t *list = CAGetSelectedNetworkList();
+
+ if (!list)
+ {
+ return CA_STATUS_FAILED;
+ }
+
+ uint8_t i = 0;
+ for (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;
+ }
+
+ CATransportAdapter_t connType = *(CATransportAdapter_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;
}
+#endif
+
+++ /dev/null
-/******************************************************************
- *
- * 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 CAErrorHandleCallback g_errorHandleCallback = NULL;
-
-static int CAGetAdapterIndex(CATransportAdapter_t cType)
-{
- switch (cType)
- {
- case CA_ADAPTER_IP:
- return 0;
- case CA_ADAPTER_RFCOMM_BTEDR:
- return 1;
- case CA_ADAPTER_GATT_BTLE:
- return 2;
- }
-
- OIC_LOG(DEBUG, TAG, "CA_CONNECTIVITY_TYPE_NUM is not 4");
-
- return -1;
-}
-
-static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportAdapter_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;
- }
-
- g_adapterHandler[index] = handler;
-
- OIC_LOG_V(DEBUG, TAG, "%d type adapter", cType);
- OIC_LOG(DEBUG, TAG, "OUT");
-}
-
-static void CAReceivedPacketCallback(CAEndpoint_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");
-}
-
-void CASetErrorHandleCallback(CAErrorHandleCallback errorCallback)
-{
- OIC_LOG(DEBUG, TAG, "Set error handle callback");
- g_errorHandleCallback = errorCallback;
-}
-
-static void CANetworkChangedCallback(CAEndpoint_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(CATransportAdapter_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(CATransportAdapter_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(CAEndpoint_t **info, uint32_t *size)
-{
- OIC_LOG(DEBUG, TAG, "IN");
- VERIFY_NON_NULL(info, TAG, "info");
- VERIFY_NON_NULL(size, TAG, "size");
-
- CAEndpoint_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
- CAEndpoint_t *resInfo = (CAEndpoint_t *)OICCalloc(resSize, sizeof(CAEndpoint_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(CAEndpoint_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 CAEndpoint_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, "Endpoint is NULL");
- return CA_STATUS_INVALID_PARAM;
- }
-
- CATransportAdapter_t type = endpoint->adapter;
-
- 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 CAEndpoint_t *endpoint, 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;
- }
-
- CATransportAdapter_t connType = *(CATransportAdapter_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(endpoint, 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;
- }
-
- CATransportAdapter_t connType = *(CATransportAdapter_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;
- }
-
- CATransportAdapter_t connType = *(CATransportAdapter_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;
- }
-
- CATransportAdapter_t connType = *(CATransportAdapter_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;
-}
-
if (NULL == resInfo)
{
OIC_LOG(ERROR, TAG, "calloc failed");
- CAAdapterFreeEndpoint(ep);
+ CAFreeEndpoint(ep);
return;
}
OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
OICFree(resInfo->info.token);
OICFree(resInfo);
- CAAdapterFreeEndpoint(ep);
+ CAFreeEndpoint(ep);
return;
}
if (NULL == cadata)
{
OIC_LOG(ERROR, TAG, "memory allocation failed !");
- CAAdapterFreeEndpoint(ep);
+ CAFreeEndpoint(ep);
OICFree(resInfo);
return;
}
if (NULL != cadata->remoteEndpoint)
{
- CADestroyEndpointInternal(cadata->remoteEndpoint);
+ CAFreeEndpoint(cadata->remoteEndpoint);
}
if (NULL != cadata->requestInfo)
OICFree(info->token);
OICFree(info->options);
OICFree(info->payload);
+ OICFree(info->resourceUri);
OICFree(cadata->errorInfo);
}
- OICFree(cadata->options);
OICFree(cadata);
OIC_LOG(DEBUG, TAG, "OUT");
}
if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
- CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
coap_delete_pdu(pdu);
return;
}
if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
- CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
coap_delete_pdu(pdu);
return;
}
}
}
- 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)
{
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);
// store the data at queue.
CAData_t *cadata = NULL;
}
cadata->type = SEND_TYPE_UNICAST;
- cadata->remoteEndpoint = CAAdapterCloneEndpoint(endpoint);
+ cadata->remoteEndpoint = CACloneEndpoint(endpoint);
cadata->requestInfo = ReqInfo;
cadata->responseInfo = NULL;
CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
if (NULL != ResInfo->info.payload)
{
- OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
+ OIC_LOG_V(DEBUG, TAG, "Response- payload: %p(%u) from %s", ResInfo->info.payload,
+ ResInfo->info.payloadSize, endpoint->addr);
}
OIC_LOG_V(DEBUG, TAG, "Response- code: %d", ResInfo->result);
- OIC_LOG_V(DEBUG, TAG, "Response- token : %s", ResInfo->info.token);
+ if (NULL != ResInfo->info.token)
+ {
+ OIC_LOG(DEBUG, TAG, "Response- token:");
+ OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ResInfo->info.token,
+ ResInfo->info.tokenLength);
+ }
OIC_LOG_V(DEBUG, TAG, "Response- msgID: %d", ResInfo->info.messageId);
// store the data at queue.
}
cadata->type = SEND_TYPE_UNICAST;
- cadata->remoteEndpoint = CAAdapterCloneEndpoint(endpoint);
+ cadata->remoteEndpoint = CACloneEndpoint(endpoint);
cadata->requestInfo = NULL;
// for retransmission
void CAHandleRequestResponseCallbacks()
{
- OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks IN");
#ifdef SINGLE_HANDLE
// parse the data and call the callbacks.
}
CADataDestroyer(msg, sizeof(CAData_t));
+ OICFree(item);
#endif
OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks OUT");
data->remoteEndpoint = remoteEndpoint;
data->requestInfo = requestInfo;
data->responseInfo = NULL;
+ data->options = NULL;
+ data->numOptions = 0;
+ if (NULL != requestInfo->info.options && 0 < requestInfo->info.numOptions)
+ {
+ uint8_t numOptions = requestInfo->info.numOptions;
+ // copy data
+ CAHeaderOption_t *headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t)
+ * numOptions);
+ CA_MEMORY_ALLOC_CHECK(headerOption);
+
+ memcpy(headerOption, requestInfo->info.options, sizeof(CAHeaderOption_t) * numOptions);
+
+ data->options = headerOption;
+ data->numOptions = numOptions;
+ }
// add thread
CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
// memory error label.
memory_error_exit:
- CAAdapterFreeEndpoint(remoteEndpoint);
+ CAFreeEndpoint(remoteEndpoint);
CADestroyRequestInfoInternal(requestInfo);
OICFree(data);
data->remoteEndpoint = remoteEndpoint;
data->requestInfo = NULL;
data->responseInfo = responseInfo;
+ data->options = NULL;
+ data->numOptions = 0;
+ if (NULL != responseInfo->info.options && 0 < responseInfo->info.numOptions)
+ {
+ uint8_t numOptions = responseInfo->info.numOptions;
+ // copy data
+ CAHeaderOption_t *headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t)
+ * numOptions);
+ CA_MEMORY_ALLOC_CHECK(headerOption);
+
+ memcpy(headerOption, responseInfo->info.options, sizeof(CAHeaderOption_t) * numOptions);
+
+ data->options = headerOption;
+ data->numOptions = numOptions;
+ }
// add thread
CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
// memory error label.
memory_error_exit:
- CAAdapterFreeEndpoint(remoteEndpoint);
+ CAFreeEndpoint(remoteEndpoint);
CADestroyResponseInfoInternal(responseInfo);
OICFree(data);
OIC_LOG(DEBUG, TAG, "OUT");
if (NULL == cadata)
{
OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
- CADestroyEndpointInternal(rep);
+ CAFreeEndpoint(rep);
OICFree(errorInfo);
coap_delete_pdu(pdu);
return;
return;
}
-
#include "cainterface.h"
#include "camessagehandler_singlethread.h"
#include "caremotehandler.h"
-#include "cainterfacecontroller_singlethread.h"
+#include "cainterfacecontroller.h"
#include "caprotocolmessage.h"
-#include "caretransmission_singlethread.h"
+#include "caretransmission.h"
#include "logger.h"
#include "config.h" /* for coap protocol */
#include "oic_malloc.h"
if (NULL == resInfo)
{
OIC_LOG(ERROR, TAG, "calloc failed");
- CADestroyEndpointInternal(ep);
+ CAFreeEndpoint(ep);
return;
}
g_responseHandler(ep, resInfo);
}
- CADestroyEndpointInternal(ep);
+ CAFreeEndpoint(ep);
OICFree(resInfo);
OIC_LOG(DEBUG, TAG, "OUT");
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(ERROR, TAG, "Parse PDU failed");
OIC_LOG(DEBUG, TAG, "token:");
OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
- if (ReqInfo)
+ if (g_requestHandler)
{
- if (g_requestHandler)
- {
- g_requestHandler(endpoint, ReqInfo);
- }
-
- CADestroyRequestInfoInternal(ReqInfo);
+ g_requestHandler(endpoint, ReqInfo);
}
+
+ CADestroyRequestInfoInternal(ReqInfo);
}
else
{
CA_MEMORY_ALLOC_CHECK(data);
// save data
- data->type = SEND_TYPE_UNICAST;
+ data->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
data->remoteEndpoint = object;
data->requestInfo = request;
data->responseInfo = NULL;
CASetNetworkChangeCallback(CANetworkChangedCallback);
// retransmission initialize
- CARetransmissionInitialize(&g_retransmissionContext, CASendUnicastData,
+ CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
CATimeoutCallback, NULL);
- CAInitializeAdapters();
+ CAInitializeAdapters(NULL);
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
#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>
coap_delete_list(optlist);
return NULL;
}
- size_t lenPayload = info->payload ? strlen(info->payload) : 0;
- pdu = CAGeneratePDUImpl((code_t)code, optlist, info, info->payload, lenPayload);
+ pdu = CAGeneratePDUImpl((code_t)code, optlist, info, info->payload, info->payloadSize);
if (NULL == pdu)
{
OIC_LOG(ERROR, TAG, "pdu NULL");
}
coap_pdu_t *CAGeneratePDUImpl(code_t code, coap_list_t *options, const CAInfo_t *info,
- const char *payload, size_t payloadSize)
+ const uint8_t *payload, size_t payloadSize)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_RET(info, TAG, "info is NULL", NULL);
if (NULL != payload)
{
- OIC_LOG_V(DEBUG, TAG, "add data, payload:%s", payload);
coap_add_data(pdu, payloadSize, (const unsigned char *) payload);
}
outInfo->tokenLength = pdu->hdr->token_length;
// set payload data
- if (NULL != pdu->data)
+ size_t dataSize;
+ uint8_t *data;
+ if (coap_get_data(pdu, &dataSize, &data))
{
- uint32_t payloadLength = strlen((char*) pdu->data);
OIC_LOG(DEBUG, TAG, "inside pdu->data");
- outInfo->payload = (char *) OICMalloc(payloadLength + 1);
+ outInfo->payload = (uint8_t *) OICMalloc(dataSize);
if (NULL == outInfo->payload)
{
OIC_LOG(ERROR, TAG, "Out of memory");
OICFree(outInfo->token);
return CA_MEMORY_ALLOC_FAILED;
}
- memcpy(outInfo->payload, pdu->data, payloadLength);
- outInfo->payload[payloadLength] = '\0';
+ memcpy(outInfo->payload, pdu->data, dataSize);
+ outInfo->payloadSize = dataSize;
}
uint32_t length = strlen(optionResult);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+
+#ifndef SINGLE_THREAD
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
+#endif
#if defined(__ANDROID__)
#include <linux/time.h>
#include "oic_malloc.h"
#include "logger.h"
-#define TAG PCF("CA")
+#define TAG "CA"
typedef struct
{
uint64_t timeStamp; /**< last sent time. microseconds */
+#ifndef SINGLE_THREAD
uint64_t timeout; /**< timeout value. microseconds */
+#endif
uint8_t triedCount; /**< retransmission count */
uint16_t messageId; /**< coap PDU message id */
CAEndpoint_t *endpoint; /**< remote endpoint */
*/
uint64_t getCurrentTimeInMicroSeconds();
+#ifndef SINGLE_THREAD
+/**
+ * @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;
+}
+
+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;
+}
+#endif
+
/**
* @brief check timeout routine
* @param currentTime [IN]microseconds
- * @param timeStamp [IN]microseconds
- * @param timeoutValue [IN]microseconds
- * @param triedCount [IN]Number of retransmission tried
+ * @param retData [IN]retransmission data
* @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)
+static bool CACheckTimeout(uint64_t currentTime, CARetransmissionData_t *retData)
{
+#ifndef SINGLE_THREAD
// #1. calculate timeout
- uint32_t milliTimeoutValue = timeoutValue * 0.001;
- uint64_t timeout = (milliTimeoutValue << triedCount) * (uint64_t) 1000;
+ uint32_t milliTimeoutValue = retData->timeout * 0.001;
+ uint64_t timeout = (milliTimeoutValue << retData->triedCount) * (uint64_t) 1000;
- if (currentTime >= timeStamp + timeout)
+ if (currentTime >= retData->timeStamp + timeout)
{
- OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%ld)", timeout, triedCount);
+ OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%ld)",
+ timeout, retData->triedCount);
return true;
}
+#else
+ // #1. calculate timeout
+ uint64_t timeOut = (2 << retData->triedCount) * 1000000;
+ if (currentTime >= retData->timeStamp + timeOut)
+ {
+ OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d",
+ (2 << retData->triedCount), retData->triedCount);
+ return true;
+ }
+#endif
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..");
+ OIC_LOG(ERROR, TAG, "context is null");
return;
}
uint64_t currentTime = getCurrentTimeInMicroSeconds();
- if (CACheckTimeout(currentTime, retData->timeStamp, retData->timeout, retData->triedCount))
+ if (CACheckTimeout(currentTime, retData))
{
// #2. if time's up, send the data.
if (NULL != context->dataSendMethod)
{
- OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, message id(%d)",
+ OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, msgid=%d",
retData->messageId);
context->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
}
if (retData->triedCount >= context->config.tryingCount)
{
CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
-
- if (NULL != removedData)
+ 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);
- }
-
- CADestroyEndpointInternal(removedData->endpoint);
- OICFree(removedData->pdu);
-
- OICFree(removedData);
-
- // modify loop value.
- len = u_arraylist_length(context->dataList);
-
- --i;
+ OIC_LOG(ERROR, TAG, "Removed data is NULL");
+ // mutex unlock
+ ca_mutex_unlock(context->threadMutex);
+ return;
}
- else
+ OIC_LOG_V(DEBUG, TAG, "max trying count, remove RTCON data,"
+ "msgid=%d", removedData->messageId);
+
+ // callback for retransmit timeout
+ if (NULL != context->timeoutCallback)
{
- OIC_LOG(ERROR, TAG, "arraylist remove error");
+ context->timeoutCallback(removedData->endpoint, removedData->pdu,
+ removedData->size);
}
+ CAFreeEndpoint(removedData->endpoint);
+ OICFree(removedData->pdu);
+
+ OICFree(removedData);
+
+ // modify loop value.
+ len = u_arraylist_length(context->dataList);
+ --i;
}
}
ca_mutex_unlock(context->threadMutex);
}
-static void CARetransmissionBaseRoutine(void *threadValue)
+void CARetransmissionBaseRoutine(void *threadValue)
{
- OIC_LOG(DEBUG, TAG, "retransmission main thread start..");
+ 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!!");
+ OIC_LOG(ERROR, TAG, "thread data passing error");
+
+ return;
+ }
+#ifdef SINGLE_THREAD
+ if (true == context->isStop)
+ {
+ OIC_LOG(DEBUG, TAG, "thread stopped");
return;
}
+ CACheckRetransmissionList(context);
+#else
while (!context->isStop)
{
ca_cond_signal(context->threadCond);
ca_mutex_unlock(context->threadMutex);
- OIC_LOG(DEBUG, TAG, "retransmission main thread end..");
+#endif
+ OIC_LOG(DEBUG, TAG, "retransmission main thread end");
}
-CAResult_t CARetransmissionInitialize(CARetransmission_t *context, ca_thread_pool_t handle,
+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..");
+ OIC_LOG(ERROR, TAG, "thread instance is empty");
return CA_STATUS_INVALID_PARAM;
}
-
+#ifndef SINGLE_THREAD
if (NULL == handle)
{
- OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
+ OIC_LOG(ERROR, TAG, "thread pool handle is empty");
return CA_STATUS_INVALID_PARAM;
}
-
- OIC_LOG(DEBUG, TAG, "thread initialize..");
+#endif
+ OIC_LOG(DEBUG, TAG, "thread initialize");
memset(context, 0, sizeof(CARetransmission_t));
{
// setDefault
cfg.supportType = DEFAULT_RETRANSMISSION_TYPE;
- cfg.tryingCount = DEFAULT_MAX_RETRANSMIT;
+ cfg.tryingCount = DEFAULT_RETRANSMISSION_COUNT;
}
else
{
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 CAEndpoint_t *endpoint,
const void *pdu, uint32_t size)
{
if (NULL == context || NULL == endpoint || NULL == pdu)
{
- OIC_LOG(ERROR, TAG, "invalid parameter..");
+ OIC_LOG(ERROR, TAG, "invalid parameter");
return CA_STATUS_INVALID_PARAM;
}
// #0. check support transport type
if (!(context->config.supportType & endpoint->adapter))
{
- OIC_LOG_V(DEBUG, TAG, "not supported transport type for retransmission..(%d)",
- endpoint->adapter);
+ OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
return CA_NOT_SUPPORTED;
}
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);
+ 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 for retransmission..");
+ OIC_LOG(DEBUG, TAG, "not supported message type");
return CA_NOT_SUPPORTED;
}
if (NULL == retData)
{
- OIC_LOG(ERROR, TAG, "memory error!!");
+ OIC_LOG(ERROR, TAG, "memory error");
return CA_MEMORY_ALLOC_FAILED;
}
if (NULL == pduData)
{
OICFree(retData);
- OIC_LOG(ERROR, TAG, "memory error!!");
+ OIC_LOG(ERROR, TAG, "memory error");
return CA_MEMORY_ALLOC_FAILED;
}
memcpy(pduData, pdu, size);
{
OICFree(retData);
OICFree(pduData);
- OIC_LOG(ERROR, TAG, "memory error!!");
+ OIC_LOG(ERROR, TAG, "memory error");
return CA_MEMORY_ALLOC_FAILED;
}
// #2. add additional information. (time stamp, retransmission count...)
retData->timeStamp = getCurrentTimeInMicroSeconds();
+#ifndef SINGLE_THREAD
retData->timeout = CAGetTimeoutValue();
+#endif
retData->triedCount = 0;
retData->messageId = messageId;
retData->endpoint = remoteEndpoint;
retData->pdu = pduData;
retData->size = size;
-
+#ifndef SINGLE_THREAD
// mutex lock
ca_mutex_lock(context->threadMutex);
// mutex unlock
ca_mutex_unlock(context->threadMutex);
+#else
+ u_arraylist_add(context->dataList, (void *) retData);
+
+ CACheckRetransmissionList(context);
+#endif
return CA_STATUS_OK;
}
const CAEndpoint_t *endpoint, const void *pdu,
uint32_t size, void **retransmissionPdu)
{
- OIC_LOG(DEBUG, TAG, "IN - CARetransmissionReceivedData");
+ OIC_LOG(DEBUG, TAG, "IN");
if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
{
- OIC_LOG(ERROR, TAG, "invalid parameter..");
+ OIC_LOG(ERROR, TAG, "invalid parameter");
return CA_STATUS_INVALID_PARAM;
}
// #0. check support transport type
if (!(context->config.supportType & endpoint->adapter))
{
- OIC_LOG_V(DEBUG, TAG, "not supported transport type for retransmission..(%d)",
- endpoint->adapter);
+ OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
return CA_STATUS_OK;
}
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);
+ OIC_LOG_V(DEBUG, TAG, "received pdu, msgtype=%d, msgid=%d", type, messageId);
if ((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
{
// if retransmission was finish..token will be unavailable.
if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
{
- OIC_LOG(DEBUG, TAG, "code is CA_EMPTY..");
+ OIC_LOG(DEBUG, TAG, "code is CA_EMPTY");
if (NULL == retData->pdu)
{
if ((*retransmissionPdu) == NULL)
{
OICFree(retData);
- OIC_LOG(ERROR, TAG, "memory error!!");
+ OIC_LOG(ERROR, TAG, "memory error");
// mutex unlock
ca_mutex_unlock(context->threadMutex);
return CA_STATUS_FAILED;
}
- OIC_LOG_V(DEBUG, TAG, "remove retransmission CON data!!, message id(%d)",
- messageId);
+ OIC_LOG_V(DEBUG, TAG, "remove RTCON data!!, msgid=%d", messageId);
- CADestroyEndpointInternal(removedData->endpoint);
+ CAFreeEndpoint(removedData->endpoint);
OICFree(removedData->pdu);
OICFree(removedData);
// mutex unlock
ca_mutex_unlock(context->threadMutex);
- OIC_LOG(DEBUG, TAG, "OUT - CARetransmissionReceivedData");
+ OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
OIC_LOG_V(DEBUG, TAG, "current time = %ld", currentTime);
+#elif defined __ARDUINO__
+ currentTime = millis() * 1000;
+ OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
#else
#if _POSIX_TIMERS > 0
struct timespec ts;
+++ /dev/null
-/******************************************************************
- *
- * 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 **/
- CAEndpoint_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);
- }
-
- CADestroyEndpointInternal(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 = {};
-
- if (NULL == config)
- {
- // setDefault
- cfg.supportType = (CATransportAdapter_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 CAEndpoint_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->adapter))
- {
- 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
- CAEndpoint_t *remoteEndpoint = CACloneEndpoint(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 CAEndpoint_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->adapter))
- {
- OIC_LOG_V(DEBUG, TAG, "not supp conntype=%d", endpoint->adapter);
- 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->adapter == endpoint->adapter))
- {
- // 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);
-
- CADestroyEndpointInternal(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;
-}
-
#######################################################
-# Building IP adapter
+# Build IP adapter
#######################################################
Import('env')
+import os.path
print "Reading IP adapter script"
secured = env.get('SECURED')
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
+# Source files to build common for all platforms
+common_files = None
if target_os == 'arduino':
- env.AppendUnique(CA_SRC=[src_dir+'caipadapter_singlethread.c'])
- env.AppendUnique(CPPPATH=[src_dir+'arduino/'])
+ common_files = [ os.path.join(src_dir,
+ 'caipadapter.c') ]
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
+ common_files = [
+ os.path.join(src_dir, 'caipadapter.c'),
+ os.path.join(src_dir, 'caipclient.c'),
+ os.path.join(src_dir, 'caipserver.c') ]
+
+# Get list of target-specific source file base names, i.e. no parent
+# directories prepended to the path.
+#
+# Target-specific SConscript files are expected to return that list.
+target_files = []
+target_sconscript = os.path.join(target_os, 'SConscript')
+
+# Check for the existence of the platform-specific SConscript file
+# relative to the top-level source directory, not the build (variant)
+# directory, before calling that SConscript file to prevent a missing
+# file warning platforms that don't provide one.
+target_sconscript_abspath = str(File(target_sconscript).srcnode().abspath)
+if os.path.exists(target_sconscript_abspath):
+ target_files = env.SConscript(target_sconscript, exports='src_dir')
+
+# Now prepend the appropriate parent directories
+# (e.g. ./ip_adapter/android) to each of the target source files in
+# the list.
+target_files = [ os.path.join(src_dir, target_os, f) for f in target_files ]
+
+# Source files to build for Linux-like platforms
if target_os in ['linux','darwin','ios']:
- env.AppendUnique(CA_SRC=[src_dir+'linux/caipnwmonitor.c'])
+ target_files += [ os.path.join(src_dir,
+ 'linux/caipnwmonitor.c') ]
+
+# The list of BLE adapter source files is a combination of both the
+# common and target-specific source file lists.
+env.AppendUnique(CA_SRC = common_files + target_files)
-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/'])
--- /dev/null
+#######################################################
+# Build IP adapter for Android
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+env.AppendUnique(CPPPATH = [ os.path.join(src_dir, 'android') ])
+
+src_files = [ 'caipnwmonitor.c' ]
+
+Return('src_files')
--- /dev/null
+#######################################################
+# Build IP adapter for Ardunino
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+env.AppendUnique(CPPPATH = [ os.path.join(src_dir, 'arduino') ])
+
+if env.get('SHIELD') == 'WIFI':
+ src_files = [ 'caipclient_wifi.cpp',
+ 'caipserver_wifi.cpp',
+ 'caipnwmonitor_wifi.cpp' ]
+else:
+ src_files = [ 'caipadapterutils_eth.cpp',
+ 'caipclient_eth.cpp',
+ 'caipserver_eth.cpp',
+ 'caipnwmonitor_eth.cpp' ]
+
+Return('src_files')
#include "logger.h"
#include "cacommon.h"
#include "caadapterinterface.h"
-#include "caipadapter_singlethread.h"
#include "caadapterutils.h"
#define TAG "IPU"
#include "logger.h"
#include "cacommon.h"
#include "caadapterinterface.h"
-#include "caipadapter_singlethread.h"
+#include "caipadapter.h"
#include "caadapterutils.h"
#ifdef __cplusplus
* limitations under the License.
*
******************************************************************/
-#include "caipinterface_singlethread.h"
+#include "caipinterface.h"
#include <Arduino.h>
#include <Ethernet.h>
#include "logger.h"
#include "cacommon.h"
#include "caadapterinterface.h"
-#include "caipadapter_singlethread.h"
+#include "caipadapter.h"
#include "caipadapterutils_eth.h"
#include "caadapterutils.h"
#include "oic_malloc.h"
return;
}
-uint32_t CAIPSendData(const char *remoteAddress, uint16_t port,
- const char *buf, uint32_t bufLen, bool isMulticast)
+uint32_t CAIPSendData(const CAEndpoint_t *endpoint, const void *buf,
+ uint32_t bufLen, bool isMulticast)
{
if (!isMulticast && 0 == g_unicastPort)
{
return 0;
}
- VERIFY_NON_NULL(buf, TAG, "buf");
- VERIFY_NON_NULL(remoteAddress, TAG, "address");
+ VERIFY_NON_NULL(endpoint, TAG, "endpoint");
int socketID = 0;
+ uint16_t port = endpoint->port;
if (isMulticast)
{
- if (CAArduinoInitMulticastUdpSocket(remoteAddress, port, g_unicastPort, &socketID)
- != CA_STATUS_OK)
+ if (CAArduinoInitMulticastUdpSocket(endpoint->addr, port,
+ g_unicastPort, &socketID) != CA_STATUS_OK)
{
OIC_LOG(ERROR, TAG, "init mcast err");
return 0;
uint32_t ret;
uint8_t ipAddr[4] = { 0 };
uint16_t parsedPort = 0;
- if (CAParseIPv4AddressInternal(remoteAddress, ipAddr, sizeof(ipAddr),
+ if (CAParseIPv4AddressInternal(endpoint->addr, ipAddr, sizeof(ipAddr),
&parsedPort) != CA_STATUS_OK)
{
OIC_LOG(ERROR, TAG, "parse fail");
* limitations under the License.
*
******************************************************************/
-#include "caipinterface_singlethread.h"
+#include "caipinterface.h"
#include <Arduino.h>
#include <WiFi.h>
#include "logger.h"
#include "cacommon.h"
#include "caadapterinterface.h"
-#include "caipadapter_singlethread.h"
+#include "caipadapter.h"
#include "caadapterutils.h"
/// This is the max buffer size between Arduino and WiFi Shield
}
-uint32_t CAIPSendData(const char *remoteAddress, uint16_t port,
- const char *data, uint32_t dataLength, bool isMulticast)
+uint32_t CAIPSendData(const CAEndpoint_t *endpoint, const void *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);
+ VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", 0);
- OIC_LOG_V(DEBUG, TAG, "remoteip: %s", remoteAddress);
- OIC_LOG_V(DEBUG, TAG, "port: %d", port);
+ OIC_LOG_V(DEBUG, TAG, "remoteip: %s", endpoint->addr);
+ OIC_LOG_V(DEBUG, TAG, "port: %d", endpoint->port);
uint8_t ip[4] = {0};
uint16_t parsedPort = 0;
- CAResult_t res = CAParseIPv4AddressInternal(remoteAddress, ip, sizeof(ip),
+ CAResult_t res = CAParseIPv4AddressInternal(endpoint->addr, ip, sizeof(ip),
&parsedPort);
if (res != CA_STATUS_OK)
{
}
IPAddress remoteIp(ip);
- Udp.beginPacket(remoteIp, (uint16_t)port);
+ Udp.beginPacket(remoteIp, endpoint->port);
uint32_t bytesWritten = 0;
while(bytesWritten < dataLength)
+++ /dev/null
-/******************************************************************
-*
-* 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;
-}
--- /dev/null
+/******************************************************************
+*
+* 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.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 "caipadapter.h"
+#include "caadapterutils.h"
+#include "oic_malloc.h"
+
+#define TAG "IPNW"
+
+CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
+{
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStartNetworkMonitor(void)
+{
+ return CA_STATUS_OK;
+}
+
+void CAIPGetSubnetMask(char *subnetMask, int32_t addrLen)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ VERIFY_NON_NULL_VOID(subnetMask, TAG, "subnetMask");
+
+ //TODO : Fix this for scenarios when this API is invoked when device is not connected
+ uint8_t rawIPAddr[4];
+ if (addrLen < CA_IPADDR_SIZE)
+ {
+ OIC_LOG(ERROR, TAG, "Invalid addrLen");
+ return;
+ }
+
+ W5100.getSubnetMask(rawIPAddr);
+ snprintf(subnetMask, addrLen, "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2],
+ rawIPAddr[3]);
+
+ OIC_LOG_V(DEBUG, TAG, "subnetMask:%s", subnetMask);
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return;
+}
+
+/// Retrieves the IP address assigned to Arduino Ethernet shield
+void CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ VERIFY_NON_NULL_VOID(address, TAG, "address");
+
+ //TODO : Fix this for scenarios when this API is invoked when device is not connected
+ uint8_t rawIPAddr[4];
+ if (addrLen < CA_IPADDR_SIZE)
+ {
+ OIC_LOG(ERROR, TAG, "Invalid addrLen");
+ return;
+ }
+
+ W5100.getIPAddress(rawIPAddr);
+ snprintf(address, addrLen, "%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;
+}
+
+CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList)
+{
+ CANetInfo_t *netInfo = (CANetInfo_t *)OICCalloc(1, sizeof(CANetInfo_t));
+ if (!netInfo)
+ {
+ OIC_LOG(ERROR, TAG, "Malloc failed");
+ return CA_STATUS_FAILED;
+ }
+
+ CAArduinoGetInterfaceAddress(netInfo->ipAddress, CA_IPADDR_SIZE);
+
+ CAIPGetSubnetMask(netInfo->subnetMask, CA_IPADDR_SIZE);
+
+ // set interface name
+ strncpy(netInfo->interfaceName, "ETH", strlen(netInfo->interfaceName));
+
+ CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)netInfo);
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, TAG, "u_arraylist_add failed");
+ return result;
+ }
+ 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;
+}
--- /dev/null
+/******************************************************************
+*
+* 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.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 "caipadapter.h"
+#include "caadapterutils.h"
+#include "oic_malloc.h"
+
+#define TAG "IPNW"
+
+CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
+{
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStartNetworkMonitor(void)
+{
+ return CA_STATUS_OK;
+}
+
+void CAIPGetSubnetMask(char *subnetMaskAddr, int32_t addrLen)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ if (WiFi.status() != WL_CONNECTED)
+ {
+ OIC_LOG(DEBUG, TAG, "No WIFI");
+ return;
+ }
+
+ VERIFY_NON_NULL_VOID(subnetMaskAddr, TAG, "Invalid Input");
+ if (addrLen < CA_IPADDR_SIZE)
+ {
+ OIC_LOG_V(ERROR, TAG, "AddrLen MUST be atleast %d", CA_IPADDR_SIZE);
+ return;
+ }
+
+ IPAddress ip = WiFi.subnetMask();
+ snprintf((char *)subnetMaskAddr, addrLen, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+
+ OIC_LOG_V(DEBUG, TAG, "Wifi shield subnet mask is: %s", subnetMaskAddr);
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return;
+}
+
+/// Retrieves the IP address assigned to Arduino WiFi shield
+void CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ if (WiFi.status() != WL_CONNECTED)
+ {
+ OIC_LOG(DEBUG, TAG, "No WIFI");
+ return;
+ }
+
+ VERIFY_NON_NULL_VOID(address, TAG, "Invalid address");
+ if (addrLen < CA_IPADDR_SIZE)
+ {
+ OIC_LOG_V(ERROR, TAG, "AddrLen MUST be atleast %d", CA_IPADDR_SIZE);
+ return;
+ }
+
+ IPAddress ip = WiFi.localIP();
+ snprintf((char *)address, addrLen, "%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;
+}
+
+CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList)
+{
+ CANetInfo_t *netInfo = (CANetInfo_t *)OICCalloc(1, sizeof(CANetInfo_t));
+ if (!netInfo)
+ {
+ OIC_LOG(ERROR, TAG, "Malloc failed");
+ return CA_STATUS_FAILED;
+ }
+
+ CAArduinoGetInterfaceAddress(netInfo->ipAddress, CA_IPADDR_SIZE);
+
+ CAIPGetSubnetMask(netInfo->subnetMask, CA_IPADDR_SIZE);
+
+ // set interface name
+ strncpy(netInfo->interfaceName, "WIFI", strlen(netInfo->interfaceName));
+
+ CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)netInfo);
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, TAG, "u_arraylist_add failed");
+ return result;
+ }
+ 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;
+}
*
******************************************************************/
-#include "caipinterface_singlethread.h"
+#include "caipinterface.h"
#include <Arduino.h>
#include <Ethernet.h>
#include "cacommon.h"
#include "cainterface.h"
#include "caadapterinterface.h"
-#include "caipadapter_singlethread.h"
+#include "caipadapter.h"
#include "caipadapterutils_eth.h"
#include "caadapterutils.h"
#include "oic_malloc.h"
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 int g_multicastSocket = 0;
/**
+ * @var g_isMulticastServerStarted
+ * @brief Flag to check if multicast server is started
+ */
+static bool g_isMulticastServerStarted = false;
+
+/**
* @var g_unicastPort
* @brief Unicast Port
*/
static uint16_t g_unicastPort = 0;
-CAResult_t CAIPInitializeServer(void)
+CAResult_t CAIPInitializeServer(const ca_thread_pool_t threadPool)
{
return CA_STATUS_OK;
}
return;
}
-CAResult_t CAIPGetUnicastServerInfo(char **ipAddress, uint16_t *port,
- int *serverID)
+uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured)
{
- return CA_STATUS_OK;
+ return g_unicastPort;
}
CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
- const bool forceStart, int *serverFD)
+ bool secured)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL(port, TAG, "port");
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)
+ int serverFD = 1;
+ if (CAArduinoInitUdpSocket(port, &serverFD) != CA_STATUS_OK)
{
OIC_LOG(DEBUG, TAG, "failed");
return CA_STATUS_FAILED;
}
g_unicastPort = *port;
- g_unicastSocket = *serverFD;
+ g_unicastSocket = serverFD;
+ CAIPSetUnicastSocket(g_unicastSocket);
+ CAIPSetUnicastPort(g_unicastPort);
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");
}
CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress,
- uint16_t multicastPort, int *serverFD)
+ uint16_t multicastPort)
{
OIC_LOG(DEBUG, TAG, "IN");
+ if (g_isMulticastServerStarted == true)
+ {
+ OIC_LOG(ERROR, TAG, "Already Started!");
+ return CA_SERVER_STARTED_ALREADY;
+ }
+ int serverFD = 1;
if (CAArduinoInitMulticastUdpSocket(multicastAddress, multicastPort, multicastPort,
- serverFD) != CA_STATUS_OK)
+ &serverFD) != CA_STATUS_OK)
{
OIC_LOG(DEBUG, TAG, "failed");
return CA_STATUS_FAILED;
}
- g_multicastSocket = *serverFD;
+ g_multicastSocket = serverFD;
+ g_isMulticastServerStarted = true;
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 CAIPStopServer(const char *interfaceAddress)
+{
+ /* For arduino, Server will be running in only one interface */
+ return CAIPStopAllServers();
+}
+
+CAResult_t CAIPStopAllServers()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ 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);
+
+ result = CAIPStopMulticastServer();
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG_V(ERROR, TAG, "stop mcast srv fail:%d", result);
+ }
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return result;
+}
+
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);
+ CAEndpoint_t ep;
+ strncpy(ep.addr, ipAddress, MAX_ADDR_STR_SIZE_CA);
+ ep.port = port;
+ ep.flags = CA_IPV4;
+ ep.adapter = CA_ADAPTER_IP;
+ g_packetReceivedCallback(&ep, data, dataLength);
}
OIC_LOG(DEBUG, TAG, "OUT");
}
// TODO
}
-void CAIPPullData()
-{
- CAArduinoCheckData();
-}
-
-/// Retrieves the IP address assigned to Arduino Ethernet shield
-CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
+void CAIPSetErrorHandleCallback(CAIPErrorHandleCallback ipErrorCallback)
{
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;
}
+void CAIPPullData()
+{
+ CAArduinoCheckData();
+}
*
******************************************************************/
-#include "caipinterface_singlethread.h"
+#include "caipinterface.h"
#include <Arduino.h>
#include <WiFi.h>
#include "cacommon.h"
#include "cainterface.h"
#include "caadapterinterface.h"
-#include "caipadapter_singlethread.h"
+#include "caipadapter.h"
#include "caadapterutils.h"
#include "oic_malloc.h"
#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 int32_t gUnicastSocket = 0;
static bool gServerRunning = false;
static WiFiUDP Udp;
+/**
+ * @var g_unicastPort
+ * @brief Unicast Port
+ */
+static uint16_t g_unicastPort = 0;
-CAResult_t CAIPInitializeServer(void)
+CAResult_t CAIPInitializeServer(const ca_thread_pool_t threadPool)
{
/**
* This API is to keep design in sync with other platforms.
*/
}
-CAResult_t CAIPGetUnicastServerInfo(char **ipAddress, uint16_t *port, int *serverID)
+uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured)
{
- /*
- * 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;
+ return g_unicastPort;
}
CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
- bool forceStart, int *serverFD)
+ bool secured)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL(port, TAG, "port");
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;
-
+ g_unicastPort = *port;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress,
- uint16_t multicastPort, int *serverFD)
+ uint16_t multicastPort)
{
// wifi shield does not support multicast
OIC_LOG(DEBUG, TAG, "IN");
return CAIPStopUnicastServer();
}
+CAResult_t CAIPStopServer(const char *interfaceAddress)
+{
+ /* For arduino, Server will be running in only one interface */
+ return CAIPStopAllServers();
+}
+
+CAResult_t CAIPStopAllServers()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ 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);
+
+ result = CAIPStopMulticastServer();
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG_V(ERROR, TAG, "stop mcast srv fail:%d", result);
+ }
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return result;
+}
+
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);
+ CAEndpoint_t ep;
+ strncpy(ep.addr, ipAddress, MAX_ADDR_STR_SIZE_CA);
+ ep.port = port;
+ ep.flags = CA_IPV4;
+ ep.adapter = CA_ADAPTER_IP;
+ gPacketReceivedCallback(&ep, data, dataLength);
OIC_LOG(DEBUG, TAG, "Notified network packet");
}
OIC_LOG(DEBUG, TAG, "OUT");
// TODO
}
-void CAIPPullData()
-{
- CAArduinoCheckData();
-}
-
-/// Retrieves the IP address assigned to Arduino WiFi shield
-CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
+void CAIPSetErrorHandleCallback(CAIPErrorHandleCallback ipErrorCallback)
{
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;
}
-
-
+void CAIPPullData()
+{
+ CAArduinoCheckData();
+}
#endif
#include "camutex.h"
#include "uarraylist.h"
+#include "caremotehandler.h"
#include "logger.h"
#include "oic_malloc.h"
#include "oic_string.h"
* @def IP_ADAPTER_TAG
* @brief Logging tag for module name
*/
-#define IP_ADAPTER_TAG "IP_ADAP"
+#define IP_ADAPTER_TAG "IPAD"
/**
* @def CA_PORT
* @brief Port to listen for incoming data
*/
-#define CA_PORT 6298
+#ifdef ARDUINO
+#define CA_PORT 55555
+#else
+#define CA_PORT 0
+#endif
/**
* @def CA_SECURE_PORT
*/
#define CA_MULTICAST_IP "224.0.1.187"
+#ifndef SINGLE_THREAD
/**
* @var CAIPData
* @brief Holds inter thread ip data information.
} CAIPData;
/**
+ * @var g_sendQueueHandle
+ * @brief Queue handle for Send Data
+ */
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
+#endif
+
+/**
* @var g_networkPacketCallback
* @brief Network Packet Received Callback to CA
*/
static CANetworkChangeCallback g_networkChangeCallback = NULL;
/**
- * @var g_sendQueueHandle
- * @brief Queue handle for Send Data
+ * @var g_errorCallback
+ * @brief error Callback to CA adapter
*/
-static CAQueueingThread_t *g_sendQueueHandle = NULL;
+static CAErrorHandleCallback g_errorCallback = NULL;
/**
* @var g_threadPool
*/
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);
+ CANetworkStatus_t status);
static void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status);
static void CAIPPacketReceivedCB(const CAEndpoint_t *endpoint,
- const void *data, uint32_t dataLength);
+ const void *data, uint32_t dataLength);
+static void CAIPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
+ uint32_t dataLength, CAResult_t result);
#ifdef __WITH_DTLS__
static uint32_t CAIPPacketSendCB(const CAEndpoint_t *endpoint,
- const void *data, uint32_t dataLength);
+ const void *data, uint32_t dataLength);
#endif
static CAResult_t CAIPStopServers();
+#ifndef SINGLE_THREAD
+
+static CAResult_t CAIPInitializeQueueHandles();
+
+static void CAIPDeinitializeQueueHandles();
+
static void CAIPSendDataThread(void *threadData);
static CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint,
- const void *data, uint32_t dataLength,
- bool isMulticast);
+ const void *data, uint32_t dataLength, bool isMulticast);
void CAFreeIPData(CAIPData *ipData);
static void CADataDestroyer(void *data, uint32_t size);
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
}
+void CAIPSendDataThread(void *threadData)
+{
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+ CAIPData *ipData = (CAIPData *) threadData;
+ uint32_t sentData = -1;
+
+ if (!ipData)
+ {
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Invalid ip data!");
+ return;
+ }
+
+ if (ipData->isMulticast)
+ {
+ //Processing for sending multicast
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Multicast Data is called");
+ strncpy(ipData->remoteEndpoint->addr, CA_MULTICAST_IP, MAX_ADDR_STR_SIZE_CA);
+ ipData->remoteEndpoint->port = CA_MCAST_PORT;
+ sentData = CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, true);
+ }
+ else
+ {
+ //Processing for sending unicast
+#ifdef __WITH_DTLS__
+ if (ipData->remoteEndpoint->flags & CA_SECURE)
+ {
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!");
+ CAResult_t result = CAAdapterNetDtlsEncrypt(ipData->remoteEndpoint,
+ ipData->data, ipData->dataLen);
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt failed!");
+ sentData = 0;
+ }
+ OIC_LOG_V(DEBUG, IP_ADAPTER_TAG,
+ "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
+ }
+ else
+ {
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Unicast Data is called");
+ sentData = CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
+ }
+#else
+ sentData = CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
+#endif
+ }
+
+ if (0 == sentData)
+ {
+ g_errorCallback(ipData->remoteEndpoint, ipData->data, ipData->dataLen,
+ CA_SEND_FAILED);
+ }
+
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+}
+
+CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint, const void *data,
+ uint32_t dataLength, bool isMulticast)
+{
+ 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 = CACloneEndpoint(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;
+
+ ipData->isMulticast = isMulticast;
+
+ return ipData;
+}
+
+void CAFreeIPData(CAIPData *ipData)
+{
+ VERIFY_NON_NULL_VOID(ipData, IP_ADAPTER_TAG, "ipData is NULL");
+
+ CAFreeEndpoint(ipData->remoteEndpoint);
+ OICFree(ipData->data);
+ OICFree(ipData);
+}
+
+void CADataDestroyer(void *data, uint32_t size)
+{
+ CAIPData *etdata = (CAIPData *) data;
+
+ CAFreeIPData(etdata);
+}
+#endif
+
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");
- CAEndpoint_t *localEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_IP, address, port);
+ CAEndpoint_t *localEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
+ CA_ADAPTER_IP,
+ address, port);
if (!localEndpoint)
{
OIC_LOG(ERROR, IP_ADAPTER_TAG, "localEndpoint creation failed!");
OIC_LOG(ERROR, IP_ADAPTER_TAG, "g_networkChangeCallback is NULL");
}
- CAAdapterFreeEndpoint(localEndpoint);
+ CAFreeEndpoint(localEndpoint);
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
}
if (CA_INTERFACE_UP == status)
{
uint16_t port = CA_PORT;
- CAResult_t ret = CAIPStartUnicastServer(ipAddress, &port, false, false);
+ CAResult_t ret = CAIPStartUnicastServer(ipAddress, &port, false);
if (CA_STATUS_OK == ret)
{
OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Unicast server started on %d port", port);
#ifdef __WITH_DTLS__
port = CA_SECURE_PORT;
- ret = CAIPStartUnicastServer(ipAddress, &port, false, true);
+ ret = CAIPStartUnicastServer(ipAddress, &port, true);
if (CA_STATUS_OK == ret)
{
OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Secure Unicast server started on %d", port);
uint32_t sentLength = CAIPSendData(endpoint, data, dataLength, false);
+ if (sentLength == 0)
+ {
+ g_errorCallback(endpoint, data, dataLength, CA_SEND_FAILED);
+ }
+
OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Successfully sent %d of encrypted data!", sentLength);
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
#endif
void CAIPPacketReceivedCB(const CAEndpoint_t *endpoint, const void *data,
- uint32_t dataLength)
+ uint32_t dataLength)
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
{
OICFree(buf);
}
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+}
+
+void CAIPErrorHandler (const CAEndpoint_t *endpoint, const void *data,
+ uint32_t dataLength, CAResult_t result)
+{
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+ VERIFY_NON_NULL_VOID(endpoint, IP_ADAPTER_TAG, "endpoint is NULL");
+
+ VERIFY_NON_NULL_VOID(data, IP_ADAPTER_TAG, "data is NULL");
+
+ void *buf = (void*)OICMalloc(sizeof(char) * dataLength);
+ if (!buf)
+ {
+ OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory Allocation failed!");
+ return;
+ }
+ memcpy(buf, data, dataLength);
+ if (g_errorCallback)
+ {
+ g_errorCallback(endpoint, buf, dataLength, result);
+ }
+ else
+ {
+ OICFree(buf);
+ }
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+
+ return;
+}
+
+int32_t CAIPSendDataInternal(const CAEndpoint_t *remoteEndpoint, const void *data,
+ uint32_t dataLength, bool isMulticast)
+{
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+#ifdef SINGLE_THREAD
+
+ // If remoteEndpoint is NULL, its Multicast, else its Unicast.
+ if(!isMulticast)
+ {
+ CAIPSendData(remoteEndpoint, data, dataLength, false);
+ }
+ else
+ {
+ CAEndpoint_t ep = { 0 };
+ strcpy(ep.addr, CA_MULTICAST_IP);
+ ep.port = CA_MCAST_PORT;
+ CAIPSendData(&ep, data, dataLength, true);
+ }
+#else
+ VERIFY_NON_NULL_RET(g_sendQueueHandle, IP_ADAPTER_TAG, "sendQueueHandle", -1);
+
+ // Create IPData to add to queue
+ CAIPData *ipData = CACreateIPData(remoteEndpoint, data, dataLength, isMulticast);
+
+ 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));
+ }
+#endif
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+ return dataLength;
}
CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
CANetworkPacketReceivedCallback networkPacketCallback,
- CANetworkChangeCallback netCallback, ca_thread_pool_t handle)
+ CANetworkChangeCallback netCallback,
+ CAErrorHandleCallback errorCallback, 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");
+#ifndef SINGLE_THREAD
VERIFY_NON_NULL(handle, IP_ADAPTER_TAG, "thread pool handle");
+#endif
g_threadPool = handle;
g_networkChangeCallback = netCallback;
g_networkPacketCallback = networkPacketCallback;
+ g_errorCallback = errorCallback;
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);
+ OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to initialize n/w monitor[%d]", ret);
return ret;
}
CAIPSetConnectionStateChangeCallback(CAIPConnectionStateCB);
}
CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB);
+ CAIPSetErrorHandleCallback(CAIPErrorHandler);
#ifdef __WITH_DTLS__
CAAdapterNetDtlsInit();
ipHandler.terminate = CATerminateIP;
registerCallback(ipHandler, CA_ADAPTER_IP);
+#ifndef SINGLE_THREAD
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");
+#endif
+ OIC_LOG(INFO, IP_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
return ret;
}
+#ifndef SINGLE_THREAD
// 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;
}
+#endif
bool retVal = CAIPIsConnected();
if (false == retVal)
return CA_STATUS_OK;
}
+#ifdef ARDUINO
+ uint16_t unicastPort = CA_PORT;
+ // Address is hardcoded as we are using Single Interface
+ ret = CAIPStartUnicastServer("0.0.0.0", &unicastPort, false);
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Start unicast serv failed[%d]", ret);
+
+ }
+#else
u_arraylist_t *netInterfaceList = u_arraylist_create();
VERIFY_NON_NULL(netInterfaceList, IP_ADAPTER_TAG, "netInterfaceList is NULL");
continue;
}
uint16_t unicastPort = CA_PORT;
- ret = CAIPStartUnicastServer(netInfo->ipAddress, &unicastPort, false, false);
+ ret = CAIPStartUnicastServer(netInfo->ipAddress, &unicastPort, false);
if (CA_STATUS_OK == ret)
{
OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Unicast server started on %d port",
#ifdef __WITH_DTLS__
unicastPort = CA_SECURE_PORT;
- ret = CAIPStartUnicastServer(netInfo->ipAddress, &unicastPort, false, true);
+ ret = CAIPStartUnicastServer(netInfo->ipAddress, &unicastPort, true);
if (CA_STATUS_OK == ret)
{
#endif
}
CAClearNetInterfaceInfoList(netInterfaceList);
+#endif
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
return ret;
}
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+ CAResult_t ret = CA_STATUS_OK;
bool retVal = CAIPIsConnected();
if (false == retVal)
{
- OIC_LOG(DEBUG, IP_ADAPTER_TAG,
- "IP not Connected. Couldn't start multicast server");
- return CA_STATUS_OK;
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IP not Connected");
+ return ret;
}
+#ifdef ARDUINO
+ //uint16_t multicastPort = CA_MCAST_PORT;
+ ret = CAIPStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, CA_MCAST_PORT);
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Start multicast failed[%d]", ret);
+ }
+#else
u_arraylist_t *netInterfaceList = u_arraylist_create();
VERIFY_NON_NULL(netInterfaceList, IP_ADAPTER_TAG, "netInterfaceList is NULL");
- CAResult_t ret = CAIPGetInterfaceInfo(&netInterfaceList);
+ 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);
+#endif
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
return ret;
}
CAResult_t CAStartIPDiscoveryServer()
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+ /* Both listening and discovery server are same */
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
return CAStartIPListeningServer();
}
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, false);
- 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;
- }
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+ return CAIPSendDataInternal(remoteEndpoint, data, dataLength, false);
}
int32_t CASendIPMulticastData(const CAEndpoint_t *endpoint, 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(endpoint, data, dataLength, true);
- 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;
- }
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+ return CAIPSendDataInternal(endpoint, data, dataLength, true);
}
CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
bool retVal = CAIPIsConnected();
if (false == retVal)
{
- OIC_LOG(ERROR, IP_ADAPTER_TAG,
- "Failed to get interface address, IP not Connected");
+ OIC_LOG(ERROR, IP_ADAPTER_TAG, "IP not Connected");
return CA_ADAPTER_NOT_ENABLED;
}
CAResult_t CAReadIPData()
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
-
+ CAIPPullData();
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
// Stop IP network monitor
CAIPStopNetworkMonitor();
+#ifndef SINGLE_THREAD
// Stop send queue thread
if (g_sendQueueHandle)
{
CAQueueingThreadStop(g_sendQueueHandle);
}
+#endif
// Stop Unicast, Secured unicast and Multicast servers running
- CAIPStopServers();
+ CAResult_t result = CAIPStopServers();
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "stop srv fail:%d", result);
+ }
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
- return CA_STATUS_OK;
+ return result;
}
void CATerminateIP()
CAIPSetConnectionStateChangeCallback(NULL);
CAIPTerminateNetworkMonitor();
+#ifndef SINGLE_THREAD
// 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 (ipData->isMulticast)
- {
- //Processing for sending multicast
- OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Multicast Data is called");
- strncpy(ipData->remoteEndpoint->addr, CA_MULTICAST_IP, MAX_ADDR_STR_SIZE_CA);
- ipData->remoteEndpoint->port = CA_MCAST_PORT;
- CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, true);
- }
- else
- {
- //Processing for sending unicast
-#ifdef __WITH_DTLS__
- if (ipData->remoteEndpoint->flags & CA_SECURE)
- {
- OIC_LOG(DEBUG, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!");
- CAResult_t result = CAAdapterNetDtlsEncrypt(ipData->remoteEndpoint,
- ipData->data, ipData->dataLen);
- if (CA_STATUS_OK != result)
- {
- OIC_LOG(ERROR, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt failed!");
- }
- OIC_LOG_V(DEBUG, IP_ADAPTER_TAG,
- "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
- }
- else
- {
- OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Unicast Data is called");
- CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
- }
-#else
- CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
#endif
- }
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
}
-
-CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint, const void *data,
- uint32_t dataLength, bool isMulticast)
-{
- 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 = CAAdapterCloneEndpoint(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;
-
- ipData->isMulticast = isMulticast;
-
- return ipData;
-}
-
-void CAFreeIPData(CAIPData *ipData)
-{
- VERIFY_NON_NULL_VOID(ipData, IP_ADAPTER_TAG, "ipData is NULL");
-
- CAAdapterFreeEndpoint(ipData->remoteEndpoint);
- OICFree(ipData->data);
- OICFree(ipData);
-}
-
-void CADataDestroyer(void *data, uint32_t size)
-{
- CAIPData *etdata = (CAIPData *) data;
-
- CAFreeIPData(etdata);
-}
-
+++ /dev/null
-/******************************************************************
- *
- * 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)
-{
- CAEndpoint_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_IPV4, address);
- if (!localEndpoint)
- {
- OIC_LOG(ERROR, TAG, "Out of memory!");
- return;
- }
- localEndpoint->port = port;
-
- if (NULL != g_networkChangeCallback)
- {
- g_networkChangeCallback(localEndpoint, status);
- }
-
- CAAdapterFreeEndpoint(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 */
- CAEndpoint_t *endPoint = CAAdapterCreateEndpoint(CA_DEFAULT_FLAGS, CA_IPV4, ipAddress, port);
- if (NULL == endPoint)
- {
- OIC_LOG(ERROR, TAG, "Out of memory!");
- return;
- }
-
- if (g_networkPacketCallback)
- {
- g_networkPacketCallback(endPoint, data, dataLength);
- }
- CAAdapterFreeEndpoint(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 CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- VERIFY_NON_NULL_RET(endpoint, TAG, "remoteEndpoint", -1);
- VERIFY_NON_NULL_RET(data, TAG, "data", -1);
- if (dataLength == 0)
- {
- OIC_LOG(ERROR, TAG, "Invalid length");
- return -1;
- }
-
- CAIPSendData(endpoint->addr, endpoint->port, data, dataLength, false);
- OIC_LOG(DEBUG, TAG, "OUT");
- return dataLength;
-}
-
-int32_t CASendIPMulticastData(const CAEndpoint_t *endpoint, 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(CAEndpoint_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)->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;
-}
-
-
{
OIC_LOG(ERROR, IP_CLIENT_TAG, "Invalid Socket Fd");
CAClearServerInfoList(tempServerInfoList);
- return len;
+ return 0;
}
OIC_LOG_V(DEBUG, IP_CLIENT_TAG, "IP unicast SendData sockFd %d", sockFd);
ca_thread_pool_t threadPool;
CAIPPacketReceivedCallback packetReceivedCallback;
CAIPExceptionCallback exceptionCallback;
+ CAIPErrorHandleCallback IPErrorCallback;
} CAAdapterIPServerContext_t;
/**
static ca_mutex g_mutexServerInfoList = NULL;
/**
- * @var g_adapterEthServerContext
+ * @var g_adapterIPServerContext
* @brief Mutex to synchronize ethenet adapter context.
*/
-static CAAdapterIPServerContext_t *g_adapterEthServerContext = NULL;
+static CAAdapterIPServerContext_t *g_adapterIPServerContext = NULL;
/**
* @var g_mutexAdapterServerContext
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)
+ if (g_adapterIPServerContext->exceptionCallback)
{
// need to make proper exception callback.
- //g_adapterEthServerContext->exceptionCallback(ctx->type);
+ //g_adapterIPServerContext->exceptionCallback(ctx->type);
}
ca_mutex_unlock(g_mutexAdapterServerContext);
}
CAEndpoint_t ep;
strncpy(ep.addr, srcIPAddress, MAX_ADDR_STR_SIZE_CA);
ep.port = srcPort;
- ep.flags = CA_IPV4;
+ ep.flags = (CATransportFlags_t)CA_IPV4 | CA_IPV6;
ep.adapter = CA_ADAPTER_IP;
if (info->endpoint.flags & CA_SECURE)
{
ca_mutex_lock(g_mutexAdapterServerContext);
- if (g_adapterEthServerContext->packetReceivedCallback)
+ if (g_adapterIPServerContext->packetReceivedCallback)
{
- g_adapterEthServerContext->packetReceivedCallback(&ep,
+ g_adapterIPServerContext->packetReceivedCallback(&ep,
recvBuffer, recvLen);
}
OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
}
-static CAResult_t CACreateSocket(int *socketFD, const char *localIp, uint16_t *port,
- bool forceBindStart)
+static CAResult_t CACreateSocket(int *socketFD, const char *localIp, uint16_t *port, bool isSecured)
{
VERIFY_NON_NULL(socketFD, IP_SERVER_TAG, "socketFD is NULL");
VERIFY_NON_NULL(localIp, IP_SERVER_TAG, "localIp is NULL");
return CA_STATUS_FAILED;
}
- if (true == forceBindStart)
+ if (0 != *port && !isSecured)
{
int setOptionOn = SOCKETOPTION;
if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &setOptionOn,
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 (-1 == bind(sock, (struct sockaddr *) &sockAddr, sizeof(sockAddr)))
+ isBound = true;
+ }
+ else if (isSecured)
+ {
+ //if secure port 5684 is occupied, trying for another port
+ serverPort = 0;
+ sockAddr.sin_port = htons(serverPort);
+ 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;
}
-
- isBound = true;
- break;
}
- if (false == isBound)
+ if (true == isBound)
+ {
+ struct sockaddr_in sin;
+ socklen_t len = sizeof(sin);
+
+ if (-1 == getsockname(sock, (struct sockaddr *)&sin, &len))
+ {
+ OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to get socket[%s]!",
+ strerror(errno));
+ close(sock);
+ return CA_STATUS_FAILED;
+ }
+ else
+ {
+ serverPort = (uint16_t) ntohs(sin.sin_port);
+ }
+ }
+ else
{
+ OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]!", strerror(errno));
close(sock);
return CA_STATUS_FAILED;
}
}
static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port,
- bool forceBindStart, bool isSecured, int *serverFD)
+ bool isSecured, int *serverFD)
{
OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
VERIFY_NON_NULL(port, IP_SERVER_TAG, "port");
- CAResult_t ret = CACreateSocket(serverFD, localAddress, port, forceBindStart);
+ CAResult_t ret = CACreateSocket(serverFD, localAddress, port, isSecured);
if (CA_STATUS_OK != ret)
{
OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create unicast socket");
ca_mutex_lock(g_mutexAdapterServerContext);
- if (!g_adapterEthServerContext)
+ if (!g_adapterIPServerContext)
{
- OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
+ OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterIPServerContext 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,
+ if (CA_STATUS_OK != ca_thread_pool_add_task(g_adapterIPServerContext->threadPool,
CAReceiveHandler, NULL ))
{
OIC_LOG(ERROR, IP_SERVER_TAG, "thread_pool_add_task failed!");
}
ca_mutex_lock(g_mutexAdapterServerContext);
- g_adapterEthServerContext = (CAAdapterIPServerContext_t *) OICCalloc(1,
+ g_adapterIPServerContext = (CAAdapterIPServerContext_t *) OICCalloc(1,
sizeof(CAAdapterIPServerContext_t));
- if (!g_adapterEthServerContext)
+ if (!g_adapterIPServerContext)
{
OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
ca_mutex_unlock(g_mutexAdapterServerContext);
return CA_MEMORY_ALLOC_FAILED;
}
- g_adapterEthServerContext->threadPool = threadPool;
+ g_adapterIPServerContext->threadPool = threadPool;
ca_mutex_unlock(g_mutexAdapterServerContext);
{
OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
ca_mutex_lock(g_mutexAdapterServerContext);
- if (!g_adapterEthServerContext)
+ if (!g_adapterIPServerContext)
{
- OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
+ OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterIPServerContext NULL");
ca_mutex_unlock(g_mutexAdapterServerContext);
return;
}
- OICFree(g_adapterEthServerContext);
- g_adapterEthServerContext = NULL;
+ OICFree(g_adapterIPServerContext);
+ g_adapterIPServerContext = NULL;
ca_mutex_unlock(g_mutexAdapterServerContext);
}
-CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
- bool forceBindStart, bool isSecured)
+CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, bool isSecured)
{
OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
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,
+ if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, isSecured,
&unicastServerFd))
{
OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to start unicast server!");
if (!isMulticastServerStarted)
{
int mulicastServerFd = -1;
- CAResult_t ret = CACreateSocket(&mulicastServerFd, multicastAddress, &port, true);
+ CAResult_t ret = CACreateSocket(&mulicastServerFd, multicastAddress, &port, false);
if (ret != CA_STATUS_OK)
{
OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create multicast socket");
return CA_STATUS_OK;
}
+void CAIPPullData()
+{
+ OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+ OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+}
+
uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured)
{
ca_mutex_lock(g_mutexServerInfoList);
ca_mutex_lock(g_mutexAdapterServerContext);
- if (!g_adapterEthServerContext)
+ if (g_adapterIPServerContext)
{
- OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
- ca_mutex_unlock(g_mutexAdapterServerContext);
- return;
+ g_adapterIPServerContext->packetReceivedCallback = callback;
+ }
+ else
+ {
+ OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterIPServerContext NULL");
+ }
+
+ ca_mutex_unlock(g_mutexAdapterServerContext);
+
+ OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+}
+
+void CAIPSetErrorHandleCallback(CAIPErrorHandleCallback ipErrorCallback)
+{
+ OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+ ca_mutex_lock(g_mutexAdapterServerContext);
+
+ if (g_adapterIPServerContext)
+ {
+ g_adapterIPServerContext->IPErrorCallback = ipErrorCallback;
}
- g_adapterEthServerContext->packetReceivedCallback = callback;
ca_mutex_unlock(g_mutexAdapterServerContext);
OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
ca_mutex_lock(g_mutexAdapterServerContext);
- if (!g_adapterEthServerContext)
+ if (g_adapterIPServerContext)
{
- OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
- ca_mutex_unlock(g_mutexAdapterServerContext);
- return;
+ g_adapterIPServerContext->exceptionCallback = callback;
+ }
+ else
+ {
+ OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterIPServerContext NULL");
}
- g_adapterEthServerContext->exceptionCallback = callback;
ca_mutex_unlock(g_mutexAdapterServerContext);
--- /dev/null
+#######################################################
+# Build IP adapter for Tizen
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+
+env.ParseConfig("pkg-config --cflags --libs capi-network-wifi")
+
+src_files = [ 'caipnwmonitor.c' ]
+
+Return('src_files')
{
OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACheckIsInterfaceInfoChanged true");
}
+ OICFree(netInfo);
OICFree(interfaceName);
OICFree(ipAddress);
return;
}
-static char* uri = NULL;
+static char* addr = NULL;
static CAEndpoint_t* tempRep = NULL;
static CARequestInfo_t requestInfo;
static CAInfo_t requestData;
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 ADDRESS[] = "10.11.12.13";
+static const uint16_t PORT = 4545;
-static const char SECURE_INFO_DATA[] =
- "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
- "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
static const char NORMAL_INFO_DATA[] =
"{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
"\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
// check return value
TEST_F(CATests, CreateRemoteEndpointTestGood)
{
- uri = (char *) URI;
+ addr = (char *) ADDRESS;
- EXPECT_EQ(CA_STATUS_OK, CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep));
+ EXPECT_EQ(CA_STATUS_OK, CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr,
+ PORT, &tempRep));
if (tempRep != NULL)
{
// check remoteEndpoint and values of remoteEndpoint
TEST_F(CATests, CreateRemoteEndpointTestValues)
{
- uri = (char *) URI;
+ addr = (char *) ADDRESS;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr, PORT, &tempRep);
EXPECT_TRUE(tempRep != NULL);
}
}
-// check return value when uri is NULL
-TEST_F(CATests, CreateRemoteEndpointTestBad)
-{
- uri = NULL;
-
- EXPECT_EQ(CA_STATUS_FAILED, CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep));
-
- if (tempRep != NULL)
- {
- CADestroyEndpoint(tempRep);
- tempRep = NULL;
- }
-}
-
// CAGerateToken TC
// check return value
TEST_F(CATests, GenerateTokenTestGood)
// check return value
TEST(SendRequestTest, DISABLED_TC_16_Positive_01)
{
- uri = (char *) URI;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
+ addr = (char *) ADDRESS;
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr, PORT, &tempRep);
memset(&requestData, 0, sizeof(CAInfo_t));
CAGenerateToken(&tempToken, tokenLength);
CADestroyToken(tempToken);
FAIL() << "requestData.payload allocation failed";
}
- snprintf(requestData.payload, length, NORMAL_INFO_DATA, "a/light");
+ snprintf((char*)requestData.payload, length, NORMAL_INFO_DATA, "a/light");
+ requestData.payloadSize = length + 1;
requestData.type = CA_MSG_NONCONFIRM;
memset(&requestInfo, 0, sizeof(CARequestInfo_t));
}
-// check return value when uri is NULL
-TEST_F(CATests, SendRequestTestWithNullURI)
-{
- uri = NULL;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &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)
- {
- CADestroyEndpoint(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;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
+ addr = (char *) ADDRESS;
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr, PORT, &tempRep);
EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequest(tempRep, NULL));
// check return value
TEST(SendResponseTest, DISABLED_TC_19_Positive_01)
{
- uri = (char *) URI;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
+ addr = (char *) ADDRESS;
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr, PORT, &tempRep);
memset(&responseData, 0, sizeof(CAInfo_t));
responseData.type = CA_MSG_NONCONFIRM;
responseData.messageId = 1;
- responseData.payload = (char *) "response payload";
+ responseData.payload = (CAPayload_t)malloc(sizeof("response payload"));
+ memcpy(responseData.payload, "response payload", sizeof("response payload"));
+ responseData.payloadSize = sizeof("response payload");
CAGenerateToken(&tempToken, tokenLength);
requestData.token = tempToken;
requestData.tokenLength = tokenLength;
memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_SUCCESS;
+ responseInfo.result = CA_CONTENT;
responseInfo.info = responseData;
EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo));
CADestroyToken(tempToken);
CADestroyEndpoint(tempRep);
+ free(responseData.payload);
tempRep = NULL;
}
-// check return value when uri is NULL
+// check return value when address is NULL as multicast
TEST(SendResponseTest, DISABLED_TC_20_Negative_01)
{
- uri = NULL;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
+ addr = NULL;
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr, 0, &tempRep);
memset(&responseData, 0, sizeof(CAInfo_t));
responseData.type = CA_MSG_NONCONFIRM;
responseData.messageId = 1;
- responseData.payload = (char *) "response payload";
+ responseData.payload = (CAPayload_t)malloc(sizeof("response payload"));
+ memcpy(responseData.payload, "response payload", sizeof("response payload"));
+ responseData.payloadSize = sizeof("response payload");
CAGenerateToken(&tempToken, tokenLength);
requestData.token = tempToken;
requestData.tokenLength = tokenLength;
memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_SUCCESS;
+ responseInfo.result = CA_CONTENT;
responseInfo.info = responseData;
- EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendResponse(tempRep, &responseInfo));
+ EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo));
CADestroyToken(tempToken);
if (tempRep != NULL)
CADestroyEndpoint(tempRep);
tempRep = NULL;
}
+ free (responseData.payload);
}
// check return value NULL is passed instead of a valid CAResponseInfo_t address
TEST_F(CATests, SendResponseTest)
{
- uri = (char *) URI;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
+ addr = (char *) ADDRESS;
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr, PORT, &tempRep);
EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendResponse(tempRep, NULL));
// check return value
TEST(SendNotificationTest, DISABLED_TC_22_Positive_01)
{
- uri = (char *) URI;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
+ addr = (char *) ADDRESS;
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr, PORT, &tempRep);
memset(&responseData, 0, sizeof(CAInfo_t));
responseData.type = CA_MSG_NONCONFIRM;
- responseData.payload = (char *) "Temp Notification Data";
+ responseData.payload = (CAPayload_t)malloc(sizeof("Temp Notification Data"));
+ memcpy(responseData.payload, "Temp Notification Data", sizeof("Temp Notification Data"));
+ responseData.payloadSize = sizeof("Temp Notification Data");
CAGenerateToken(&tempToken, tokenLength);
requestData.token = tempToken;
requestData.tokenLength = tokenLength;
memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_SUCCESS;
+ responseInfo.result = CA_CONTENT;
responseInfo.info = responseData;
EXPECT_EQ(CA_STATUS_OK, CASendNotification(tempRep, &responseInfo));
CADestroyEndpoint(tempRep);
tempRep = NULL;
}
-}
-
-// check return value when uri is NULL
-TEST_F(CATests, SendNotificationTest)
-{
- uri = NULL;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &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)
- {
- CADestroyEndpoint(tempRep);
- tempRep = NULL;
- }
+ free(responseData.payload);
}
// CASelectNewwork TC
namespace {
-static const char COAP_HEADER[] = "coap://[::]/";
-
class CoAPOptionCase
{
public:
verifyParsedOptions(cases, numCases, optlist);
+ coap_delete_list(optlist);
}
// Try for multiple URI path components that still total less than 128
verifyParsedOptions(cases, numCases, optlist);
+ coap_delete_list(optlist);
}
// Try for multiple URI parameters that still total less than 128
verifyParsedOptions(cases, numCases, optlist);
+ coap_delete_list(optlist);
}
// Test that an initial long path component won't hide latter ones.
verifyParsedOptions(cases, numCases, optlist);
+ coap_delete_list(optlist);
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#ifndef _RANDOM_H
-#define _RANDOM_H
+#ifndef OC_RANDOM_H
+#define OC_RANDOM_H
#include <stdint.h>
#include <stdlib.h>
}
#endif
-#endif //_RANDOM_H
+#endif // OC_RANDOM_H
if target_os not in ['arduino', 'windows', 'winrt']:
libocsrm_env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
libocsrm_env.AppendUnique(CFLAGS = ['-std=c99'])
+ libocsrm_env.AppendUnique(CPPDEFINES = ['HAVE_STRINGS_H'])
if target_os not in ['windows', 'winrt']:
libocsrm_env.AppendUnique(CFLAGS = ['-Wall'])
libocsrm = libocsrm_env.StaticLibrary('libocsrm', libocsrm_src)
libocsrm_env.InstallTarget(libocsrm, 'libocsrm')
+libocsrm_env.UserInstallTargetLib(libocsrm, 'libocsrm')
if env.get('SECURED') == '1':
SConscript('provisioning/SConscript')
extern const char * SVR_DB_FILE_NAME;
extern const char * OIC_MI_DEF;
-extern const char * OIC_RSRC_CORE_URI;
-extern const char * OIC_RSRC_CORE_D_URI;
-extern const char * OIC_RSRC_CORE_P_URI;
-extern const char * OIC_RSRC_PRESENCE_URI;
-extern const char * OIC_RSRC_TYPES_D_URI;
-
//ACL
extern const char * OIC_RSRC_TYPE_SEC_ACL;
extern const char * OIC_RSRC_ACL_URI;
######################################################################
provisioning_env.AppendUnique(CPPPATH = [
'../../stack/include',
+ '../../stack/include/internal',
'../../ocrandom/include',
'../../logger/include',
'../../../oc_logger/include',
provisioningserver = provisioning_env.StaticLibrary('ocspapi', provisioning_src)
provisioning_env.InstallTarget(provisioningserver, 'libocspapi')
+provisioning_env.UserInstallTargetLib(provisioningserver, 'libocspapi')
if target_os in ['linux']:
SConscript('sample/SConscript')
#include <stdbool.h>
#include "cJSON.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
#include "oic_malloc.h"
#include "logger.h"
#include "cacommon.h"
const char *resourceUri,
char *payload, int payloadLen)
{
+ if (payload && '\0' != (*(payload + payloadLen)))
+ {
+ OC_LOG(ERROR, TAG, "Payload not properly terminated.");
+ return CA_STATUS_INVALID_PARAM;
+ }
+
if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
{
OC_LOG(ERROR, TAG, "Error while generating token");
CADestroyEndpoint(endpoint);
return CA_STATUS_FAILED;
}
- CAMessageType_t msgType = CA_MSG_CONFIRM;
- CAInfo_t requestData = { 0 };
- requestData.token = gToken;
- requestData.tokenLength = CA_MAX_TOKEN_LEN;
- if (payload && '\0' != (*(payload + payloadLen)))
- {
- OC_LOG(ERROR, TAG, "Payload not properly terminated.");
- CADestroyEndpoint(endpoint);
- return CA_STATUS_INVALID_PARAM;
- }
- requestData.payload = payload;
- requestData.type = msgType;
- requestData.resourceUri = (CAURI_t)resourceUri;
- CARequestInfo_t requestInfo = { 0 };
+ OCSecurityPayload secPayload = {};
+ secPayload.securityData = payload;
+ secPayload.base.type = PAYLOAD_TYPE_SECURITY;
+
+ CARequestInfo_t requestInfo = {};
requestInfo.method = method;
- requestInfo.info = requestData;
requestInfo.isMulticast = false;
+ OCConvertPayload((OCPayload*)(&secPayload), &requestInfo.info.payload,
+ &requestInfo.info.payloadSize);
+
+ requestInfo.info.type = CA_MSG_CONFIRM;
+ requestInfo.info.token = gToken;
+ requestInfo.info.tokenLength = CA_MAX_TOKEN_LEN;
+ requestInfo.info.resourceUri = (CAURI_t)resourceUri;
+
CAResult_t caResult = CA_STATUS_OK;
caResult = CASendRequest(endpoint, &requestInfo);
if (CA_STATUS_OK != caResult)
memcpy(&(ptr->endpoint), endpoint, sizeof(CAEndpoint_t));
ptr->doxm = doxm;
+
ptr->next = NULL;
if (NULL == gStartOfDiscoveredDevices)
}
else
{
- // temp logic for trimming oc attribute from the json.
- // JSONToBin should handle oc attribute.
- char *pTempPayload = (char *)OICMalloc(strlen(responseInfo->info.payload));
- if (NULL == pTempPayload)
+ OCPayload* payload;
+ OCStackResult result = OCParsePayload(&payload, responseInfo->info.payload,
+ responseInfo->info.payloadSize);
+
+ OicSecDoxm_t *ptrDoxm = NULL;
+
+ if(result == OC_STACK_OK && payload->type == PAYLOAD_TYPE_SECURITY)
{
- OC_LOG(ERROR, TAG, "Error while Memory allocation.");
- gStateManager = gStateManager | SP_DISCOVERY_ERROR;
- return true;
+ ptrDoxm = JSONToDoxmBin(((OCSecurityPayload*)payload)->securityData);
}
- strcpy(pTempPayload, responseInfo->info.payload + 8);
- pTempPayload[strlen(pTempPayload) - 2] = '\0';
- OC_LOG_V(DEBUG, TAG, "Trimmed payload: %s", pTempPayload);
- OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(pTempPayload);
- OICFree(pTempPayload);
-
if (NULL == ptrDoxm)
{
OC_LOG(INFO, TAG, "Ignoring malformed JSON");
return true;
}
- char *pTempPayload = (char *)OICMalloc(strlen(responseInfo->info.payload));
- if (NULL == pTempPayload)
+ OCPayload* payload;
+ OCStackResult result = OCParsePayload(&payload, responseInfo->info.payload,
+ responseInfo->info.payloadSize);
+
+ OicSecPstat_t *pstat = NULL;
+
+ if(result == OC_STACK_OK && payload->type == PAYLOAD_TYPE_SECURITY)
{
- OC_LOG(ERROR, TAG, "Error in memory allocation.");
- gStateManager |= SP_LIST_METHODS_ERROR;
- return true;
+ pstat = JSONToPstatBin(((OCSecurityPayload*)payload)->securityData);
}
- strcpy(pTempPayload, responseInfo->info.payload + 8);
- pTempPayload[strlen(pTempPayload) - 2] = '\0';
-
- OicSecPstat_t *pstat = JSONToPstatBin(pTempPayload);
if (NULL == pstat)
{
OC_LOG(ERROR, TAG, "Error while converting json to pstat bin");
- OICFree(pTempPayload);
gStateManager |= SP_LIST_METHODS_ERROR;
return true;
}
- OICFree(pTempPayload);
DeletePstatBinData(gPstat);
gPstat = pstat;
requestData.token = gToken;
requestData.tokenLength = CA_MAX_TOKEN_LEN;
requestData.payload = NULL;
+ requestData.payloadSize = 0;
requestData.type = msgType;
requestData.resourceUri = DOXM_OWNED_FALSE_MULTICAST_QUERY;
CARequestInfo_t requestInfo = { 0 };
OCEntityHandlerResult ehRet = OC_EH_ERROR;
// Convert JSON ACL data into binary. This will also validate the ACL data received.
- OicSecAcl_t* newAcl = JSONToAclBin((char *)(ehRequest->reqJSONPayload));
+ OicSecAcl_t* newAcl = JSONToAclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
if (newAcl)
{
*/
const char *rsrcs[] = {
- OIC_RSRC_CORE_URI,
- OIC_RSRC_CORE_D_URI,
- OIC_RSRC_CORE_P_URI,
- OIC_RSRC_TYPES_D_URI,
- OIC_RSRC_PRESENCE_URI,
+ OC_RSRVD_WELL_KNOWN_URI,
+ OC_RSRVD_DEVICE_URI,
+ OC_RSRVD_PLATFORM_URI,
+ OC_RSRVD_RESOURCE_TYPES_URI,
+#ifdef WITH_PRESENCE
+ OC_RSRVD_PRESENCE_URI,
+#endif //WITH_PRESENCE
OIC_RSRC_ACL_URI,
OIC_RSRC_DOXM_URI,
OIC_RSRC_PSTAT_URI,
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#define __STDC_LIMIT_MACROS
#include "ocstack.h"
#include "logger.h"
#include "oic_malloc.h"
#include "cainterface.h"
#include <stdlib.h>
#include <string.h>
+#include <stdint.h>
+
#define TAG PCF("SRM-CREDL")
//CredId -- Mandatory
jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
- VERIFY_NON_NULL(TAG, jsonObj, ERROR);
- VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR)
- cred->credId = jsonObj->valueint;
+ if(jsonObj)
+ {
+ VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+ cred->credId = jsonObj->valueint;
+ }
//subject -- Mandatory
jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
VERIFY_NON_NULL(TAG, jsonObj, ERROR);
- VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR)
+ VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
outLen = 0;
memset(base64Buff, 0, sizeof(base64Buff));
b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
//CredType -- Mandatory
jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
VERIFY_NON_NULL(TAG, jsonObj, ERROR);
- VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR)
+ VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
cred->credType = jsonObj->valueint;
//PrivateData is mandatory for some of the credential types listed below.
* @param credType credential type.
* @param publicData public data such as public key.
* @param privateData private data such as private key.
+ * The privateData is expected in base64 encoded format.
* @param ownersLen length of owners array
* @param owners array of owners.
*
OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
VERIFY_NON_NULL(TAG, cred, ERROR);
- //TODO:Need more clarification on credId
- OCFillRandomMem((uint8_t*)&cred->credId, sizeof(cred->credId));
+ //CredId is assigned before appending new cred to the existing
+ //credential list and updating svr database in AddCredential().
+ cred->credId = 0;
VERIFY_NON_NULL(TAG, subject, ERROR);
memcpy(cred->subject.id, subject->id , sizeof(cred->subject.id));
- //TODO: check credType has one of the values {0, 1, 2, 4, 6, 8, 16}
+ VERIFY_SUCCESS(TAG, credType < (NO_SECURITY_MODE | SYMMETRIC_PAIR_WISE_KEY |
+ SYMMETRIC_GROUP_KEY | ASYMMETRIC_KEY | SIGNED_ASYMMETRIC_KEY | PIN_PASSWORD), ERROR);
cred->credType = credType;
#if 0
return cred;
}
+/*
+ * Compare function used LL_SORT for sorting credentials
+ *
+ * @param first pointer to OicSecCred_t struct
+ * @param second pointer to OicSecCred_t struct
+ *
+ *@retval
+ * -1 if credId of first is less than credId of second
+ * 0 if credId of first is equal to credId of second
+ * 1 if credId of first is greater than credId of second
+ */
+static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
+{
+ if(first->credId < second->credId)
+ {
+ return -1;
+ }
+ else if(first->credId > second->credId)
+ {
+ return 1;
+ }
+ else
+ return 0;
+}
+
+/**
+ * GetCredId goes through the cred list and returns the next
+ * available credId. The next credId could be the credId that is
+ * available due deletion of OicSecCred_t object or one more than
+ * credId of last credential in the list.
+ *
+ * @retval
+ * next available credId - success
+ * 0 - error
+ */
+
+static uint16_t GetCredId()
+{
+ //Sorts credential list in incremental order of credId
+ LL_SORT(gCred, CmpCredId);
+
+
+ OicSecCred_t *currentCred = NULL, *credTmp = NULL;
+ uint16_t nextCredId = 1;
+
+ LL_FOREACH_SAFE(gCred, currentCred, credTmp)
+ {
+ if(currentCred->credId == nextCredId)
+ {
+ nextCredId += 1;
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ VERIFY_SUCCESS(TAG, nextCredId < UINT16_MAX, ERROR);
+ return nextCredId;
+
+exit:
+ return 0;
+}
/**
* This function adds the new cred to the credential list.
*
OCStackResult AddCredential(OicSecCred_t * newCred)
{
OCStackResult ret = OC_STACK_ERROR;
+ char * jsonStr = NULL;
- if(NULL == newCred)
- {
- return OC_STACK_ERROR;
- }
+ VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);
+
+ //Assigning credId to the newCred
+ newCred->credId = GetCredId();
+
+ VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
//Append the new Cred to existing list
LL_APPEND(gCred, newCred);
//Convert CredList to JSON and update the persistent Storage
- char * jsonStr = BinToCredJSON(gCred);
+ jsonStr = BinToCredJSON(gCred);
if(jsonStr)
{
cJSON_Delete(jsonCred);
}
+exit:
return ret;
}
OCEntityHandlerResult ret = OC_EH_ERROR;
//Get binary representation of json
- OicSecCred_t * cred = JSONToCredBin((char *)ehRequest->reqJSONPayload);
+ OicSecCred_t * cred = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
if(cred)
{
- //Append the new Cred to existing list
+ //If the Post request credential has credId, it will be
+ //discarded and the next available credId will be assigned
+ //to it before getting appended to the existing credential
+ //list and updating svr database.
ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
}
#include <stdlib.h>
#include <string.h>
+#if HAVE_STRINGS_H
+#include <strings.h>
+#endif
+
#define TAG PCF("SRM-DOXM")
static OicSecDoxm_t *gDoxm = NULL;
if(jsonObj)
{
VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
- if(jsonObj && cJSON_String == jsonObj->type)
+ if(cJSON_String == jsonObj->type)
{
//Check for empty string, in case DeviceId field has not been set yet
if (jsonObj->valuestring[0])
return doxm;
}
+/**
+ * @todo document this function including why code might need to call this.
+ * The current suspicion is that it's not being called as much as it should.
+ */
static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
{
bool bRet = false;
* Convert JSON Doxm data into binary. This will also validate
* the Doxm data received.
*/
- OicSecDoxm_t* newDoxm = JSONToDoxmBin((char *)(ehRequest->reqJSONPayload));
+ OicSecDoxm_t* newDoxm = JSONToDoxmBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
if (newDoxm)
{
*/
void CheckDeviceID()
{
- //TODO: Save this deviceID at secure location so that we can retrieve it if the
- //JSON gets corrupted.
if(strcmp((char *)gDoxm->deviceID.id, "") == 0 )
{
OCFillRandomMem(gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id));
+ UpdatePersistentStorage(gDoxm);
}
}
{
OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): getting ACL..."));
currentAcl = GetACLResourceData(context->subject, &savePtr);
- char *tmp = (char*)OICMalloc(sizeof(OicUuid_t) +1);
- memcpy(tmp, context->subject, sizeof(OicUuid_t));
- tmp[sizeof(OicUuid_t) + 1] = '\0';
if(NULL != currentAcl)
{
// Found the subject, so how about resource?
}
}
while((NULL != currentAcl) && (false == context->matchingAclFound));
- }
- if(IsAccessGranted(context->retVal))
- {
- OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
- Leaving ProcessAccessRequest(ACCESS_GRANTED)"));
+
+ if(IsAccessGranted(context->retVal))
+ {
+ OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
+ Leaving ProcessAccessRequest(ACCESS_GRANTED)"));
+ }
+ else
+ {
+ OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
+ Leaving ProcessAccessRequest(ACCESS_DENIED)"));
+ }
}
else
{
OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
- Leaving ProcessAccessRequest(ACCESS_DENIED)"));
+ Leaving ProcessAccessRequest(context is NULL)"));
}
+
}
/**
if (ehRequest->resource)
{
- postJson = cJSON_Parse((char *) ehRequest->reqJSONPayload);
+ postJson = cJSON_Parse(((OCSecurityPayload*)ehRequest->payload)->securityData);
VERIFY_NON_NULL(TAG, postJson, INFO);
cJSON *jsonPstat = cJSON_GetObjectItem(postJson, OIC_JSON_PSTAT_NAME);
VERIFY_NON_NULL(TAG, jsonPstat, INFO);
#include "doxmresource.h"
#include "credresource.h"
#include "oic_malloc.h"
+#include "oic_string.h"
#include "logger.h"
#include "utlist.h"
#include <string.h>
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ehRet;
- response.payload = (char *)rspPayload;
- response.payloadSize = (rspPayload ? strlen(rspPayload) : 0);
+ response.payload = (OCPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+ response.payload->type = PAYLOAD_TYPE_SECURITY;
+ ((OCSecurityPayload*)response.payload)->securityData = OICStrdup(rspPayload);
response.persistentBufferFlag = 0;
return OCDoResponse(&response);
const char * SVR_DB_FILE_NAME = "oic_svr_db.json";
const char * OIC_MI_DEF = "oic.mi.def";
-const char * OIC_RSRC_CORE_URI = "/oic/res";
-const char * OIC_RSRC_CORE_D_URI = "/oic/res/d";
-const char * OIC_RSRC_CORE_P_URI = "/oic/p";
-const char * OIC_RSRC_PRESENCE_URI = "/oic/ad";
-const char * OIC_RSRC_TYPES_D_URI = "/oic/res/types/d";
-
//ACL
const char * OIC_RSRC_TYPE_SEC_ACL = "oic.sec.acl";
const char * OIC_RSRC_ACL_URI = "/oic/sec/acl";
char * jsonStr2 = BinToAclJSON(acl);
EXPECT_TRUE(NULL != jsonStr2);
- if (jsonStr1 && jsonStr2)
- {
- EXPECT_STREQ(jsonStr1, jsonStr2);
- }
+ EXPECT_STREQ(jsonStr1, jsonStr2);
OICFree(jsonStr1);
OICFree(jsonStr2);
// Create Entity Handler POST request payload
ehReq.method = OC_REST_POST;
- ehReq.reqJSONPayload = jsonStr;
+ ehReq.payload = (OCPayload*)calloc(1, sizeof(OCSecurityPayload));
+ ehReq.payload->type = PAYLOAD_TYPE_SECURITY;
+ ((OCSecurityPayload*)ehReq.payload)->securityData = jsonStr;
OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
EXPECT_TRUE(OC_EH_ERROR == ehRet);
#include "securevirtualresourcetypes.h"
#include "credresource.h"
#include "oic_malloc.h"
+#include "oic_string.h"
+#include "logger.h"
+
+#define TAG PCF("SRM-CRED-UT")
#ifdef __cplusplus
extern "C" {
OicSecCred_t * JSONToCredBin(const char * jsonStr);
void InitSecCredInstance(OicSecCred_t * cred);
void DeleteCredList(OicSecCred_t* cred);
+const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject);
#ifdef __cplusplus
}
#endif
{
OicSecCred_t * cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
cred->credId = 1234;
- strcpy((char *)cred->subject.id, "subject1");
+ OICStrcpy((char *)cred->subject.id, sizeof(cred->subject.id), "subject1");
#if 0
cred->roleIdsLen = 2;
cred->roleIds = (OicSecRole_t *)OICCalloc(cred->roleIdsLen, sizeof(OicSecRole_t));
- strcpy((char *)cred->roleIds[0].id, "role11");
- strcpy((char *)cred->roleIds[1].id, "role12");
+ OICStrcpy((char *)cred->roleIds[0].id, sizeof(cred->roleIds[0].id), "role11");
+ OICStrcpy((char *)cred->roleIds[1].id, sizeof(cred->roleIds[1].id), "role12");
#endif
cred->credType = 1;
cred->ownersLen = 1;
cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
- strcpy((char *)cred->owners[0].id, "ownersId11");
+ OICStrcpy((char *)cred->owners[0].id, sizeof(cred->owners[0].id), "ownersId11");
cred->next = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
cred->next->credId = 5678;
- strcpy((char *)cred->next->subject.id, "subject2");
+ OICStrcpy((char *)cred->next->subject.id, sizeof(cred->next->subject.id), "subject2");
#if 0
cred->next->roleIdsLen = 0;
#endif
cred->next->credType = 1;
- cred->next->privateData.data = (char *)OICCalloc(1, strlen("My private Key21") + 1);
- strcpy(cred->next->privateData.data, "My private Key21");
+ size_t data_size = strlen("My private Key21") + 1;
+ cred->next->privateData.data = (char *)OICCalloc(1, data_size);
+ OICStrcpy(cred->next->privateData.data, data_size,"My private Key21");
#if 0
cred->next->publicData.data = (char *)OICCalloc(1, strlen("My Public Key123") + 1);
- strcpy(cred->next->publicData.data, "My Public Key123");
+ OICStrcpy(cred->next->publicData.data, sizeof(cred->next->publicData.data),"My Public Key123");
#endif
cred->next->ownersLen = 2;
cred->next->owners = (OicUuid_t*)OICCalloc(cred->next->ownersLen, sizeof(OicUuid_t));
- strcpy((char *)cred->next->owners[0].id, "ownersId21");
- strcpy((char *)cred->next->owners[1].id, "ownersId22");
+ OICStrcpy((char *)cred->next->owners[0].id, sizeof(cred->next->owners[0].id), "ownersId21");
+ OICStrcpy((char *)cred->next->owners[1].id, sizeof(cred->next->owners[1].id), "ownersId22");
return cred;
}
+static void printCred(const OicSecCred_t * cred)
+{
+ EXPECT_TRUE(NULL != cred);
+
+ const OicSecCred_t *credTmp1 = NULL;
+ for(credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
+ {
+ OC_LOG_V(INFO, TAG, PCF("\ncred->credId = %d"), credTmp1->credId);
+ OC_LOG_V(INFO, TAG, PCF("cred->subject.id = %s"), credTmp1->subject.id);
+ OC_LOG_V(INFO, TAG, PCF("cred->credType = %d"), credTmp1->credType);
+ if(credTmp1->privateData.data)
+ {
+ OC_LOG_V(INFO, TAG, PCF("cred->privateData.data = %s"), credTmp1->privateData.data);
+ }
+ if(credTmp1->publicData.data)
+ {
+ OC_LOG_V(INFO, TAG, PCF("cred->publicData.data = %s"), credTmp1->publicData.data);
+ }
+ OC_LOG_V(INFO, TAG, PCF("cred->ownersLen = %zd"), credTmp1->ownersLen);
+ for(size_t i = 0; i < cred->ownersLen; i++)
+ {
+ OC_LOG_V(INFO, TAG, PCF("cred->owners[%zd].id = %s"), i, credTmp1->owners[i].id);
+ }
+ }
+}
+
//InitCredResource Tests
TEST(InitCredResourceTest, InitCredResource)
{
TEST(CredGenerateCredentialTest, GenerateCredentialValidInput)
{
OicUuid_t owners[1];
- strcpy((char *)owners[0].id, "ownersId21");
+ OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId21");
OicUuid_t subject = {};
- strcpy((char *)subject.id, "subject11");
+ OICStrcpy((char *)subject.id, sizeof(subject.id), "subject11");
char privateKey[] = "My private Key11";
cred = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
privateKey, 1, owners);
- printf("cred->credId = %d\n", cred->credId);
- printf("cred->subject.id = %s\n", cred->subject.id);
- printf("cred->credType = %d\n", cred->credType);
- printf("cred->privateData.data = %s\n", cred->privateData.data);
- printf("cred->ownersLen = %zd\n", cred->ownersLen);
- printf("cred->owners[0].id = %s\n", cred->owners[0].id);
+ printCred(cred);
- EXPECT_TRUE(NULL != cred);
DeleteCredList(cred);
}
-TEST(CredAddCredentialTest, GenerateCredentialValidInput)
+TEST(GenerateAndAddCredentialTest, GenerateAndAddCredentialValidInput)
{
OicUuid_t owners[1];
- strcpy((char *)owners[0].id, "ownersId21");
+ OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId11");
OicUuid_t subject = {};
- strcpy((char *)subject.id, "subject11");
+ OICStrcpy((char *)subject.id, sizeof(subject.id), "subject11");
char privateKey[] = "My private Key11";
- OicSecCred_t * cred = NULL;
+ OicSecCred_t * cred1 = NULL;
+ OicSecCred_t * headCred = NULL;
- cred = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
+ cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
privateKey, 1, owners);
- EXPECT_TRUE(NULL != cred);
- EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred));
+ EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+ headCred = cred1;
- DeleteCredList(cred);
+ OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId22");
+ OICStrcpy((char *)subject.id, sizeof(subject.id), "subject22");
+ cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
+ privateKey, 1, owners);
+ EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+
+ OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId33");
+ OICStrcpy((char *)subject.id, sizeof(subject.id), "subject33");
+ cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
+ privateKey, 1, owners);
+ EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+
+ const OicSecCred_t* credList = GetCredResourceData(&headCred->subject);
+
+ printCred(credList);
+
+ DeleteCredList(headCred);
}
+
#if 0
TEST(CredGetResourceDataTest, GetCredResourceDataValidSubject)
{
{
OCEntityHandlerRequest req;
req.method = OC_REST_POST;
- req.reqJSONPayload = (char*)"{ \"pstat\": { \"tm\": 0, \"om\": 3 }}";
+ req.payload = (OCPayload*)calloc(1, sizeof(OCSecurityPayload));
+ req.payload->type = PAYLOAD_TYPE_SECURITY;
+ ((OCSecurityPayload*)req.payload)->securityData =
+ (char*)"{ \"pstat\": { \"tm\": 0, \"om\": 3 }}";
EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
}
printf("\n");
while(GetNextQuery(&parseIter))
{
- EXPECT_NE(0, parseIter.pi.segment_length);
+ EXPECT_NE(static_cast<size_t>(0), parseIter.pi.segment_length);
strncpy(attr, (char *)parseIter.attrPos, parseIter.attrLen);
strncpy(val, (char *)parseIter.valPos, parseIter.valLen);
* @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 payload - OCRepresentationPayload object representing the message
* @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,
- const char *notificationJSONPayload, uint32_t maxAge,
+ const OCRepPayload *payload, uint32_t maxAge,
OCQualityOfService qos);
/**
--- /dev/null
+//******************************************************************
+//
+// 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_PAYLOAD_CBOR_H
+#define OC_PAYLOAD_CBOR_H
+
+#include "octypes.h"
+
+OCStackResult OCParsePayload(OCPayload** outPayload, const uint8_t* payload, size_t payloadSize);
+
+OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size);
+#endif
/*** Future placeholder for access control and policy ***/
} OCResourceInterface;
-typedef struct rsrc_t {
- struct rsrc_t *next; // Points to next resource in list
+typedef struct OCResource {
+ struct OCResource *next; // Points to next resource in list
// Relative path on the device; will be combined with base url to create fully qualified path
char *uri;
OCResourceType *rsrcType; // Resource type(s); linked list
OCAttribute *rsrcAttributes; // Resource interface(s); linked list
// Array of pointers to resources; can be used to represent a container of resources
// (i.e. hierarchies of resources) or for reference resources (i.e. for a resource collection)
- struct rsrc_t *rsrcResources[MAX_CONTAINED_RESOURCES];
+ struct OCResource *rsrcResources[MAX_CONTAINED_RESOURCES];
//struct rsrc_t *rsrcResources;
// Pointer to function that handles the entity bound to the resource.
// This handler has to be explicitly defined by the programmer
#define OC_JSON_SUFFIX_LEN (sizeof(OC_JSON_SUFFIX) - 1)
#define OC_JSON_SEPARATOR ','
#define OC_JSON_SEPARATOR_STR ","
+#define OC_KEY_VALUE_DELIMITER "="
/**
* Static values for various JSON attributes.
#define OC_RESOURCE_SECURE 1
/**
+ * OIC Virtual resources supported by every OIC device.
+ */
+typedef enum
+{
+ OC_UNKNOWN_URI =0,
+ OC_WELL_KNOWN_URI, ///< "/oic/res"
+ OC_DEVICE_URI, ///< "/oic/d"
+ OC_PLATFORM_URI, ///< "/oic/p"
+ OC_RESOURCE_TYPES_URI, ///< "/oic/res/types/d"
+#ifdef WITH_PRESENCE
+ OC_PRESENCE, ///< "/oic/ad"
+#endif
+} OCVirtualResources;
+
+/**
* The type of query a request/response message is.
*/
typedef enum
OCEntityHandlerRequest * request, void* callbackParam);
/**
- * 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.
*/
* Prepares a JSON string for response.
*/
OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
- uint8_t filterOn,
- const char *filterValue,
- char * out,
- uint16_t *remaining,
+ OCDiscoveryPayload* payload,
CATransportAdapter_t adapter);
/**
// Flag indicating slow response
uint8_t slowFlag;
uint8_t notificationFlag;
- // reqJSON is retrieved from the payload of the received request PDU
- char reqJSONPayload[1];
+ size_t payloadSize;
+ // payload is retrieved from the payload of the received request PDU
+ uint8_t payload[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
- char *payload;
- uint16_t remainingPayloadSize;
+ OCPayload* payload;
OCRequestHandle requestHandle;
} OCServerResponse;
uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
OCQualityOfService qos, char * query,
OCHeaderOption * rcvdVendorSpecificHeaderOptions,
- char * reqJSONPayload, CAToken_t requestToken,
+ uint8_t * payload, CAToken_t requestToken,
uint8_t tokenLength,
char * resourceUrl, size_t reqTotalSize,
const OCDevAddr *devAddr);
* @param method - RESTful method
* @param resource - resource handle
* @param queryBuf - resource query of request
- * @param bufReqPayload - JSON payload of request
+ * @param payload - payload of request
+ * @param payloadSize - size of the payload request
* @param numVendorOptions - number of vendor options
* @param vendorOptions - vendor options
* @param observeAction - observe action flag
* @return
* OCStackResult
*/
-OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerRequest, OCRequestHandle request,
- OCMethod method, OCResourceHandle resource, char * queryBuf, char * bufReqPayload,
+OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerRequest,
+ OCRequestHandle request,
+ OCMethod method, OCResourceHandle resource, char * queryBuf,
+ uint8_t * payload, size_t payloadSize,
uint8_t numVendorOptions, OCHeaderOption * vendorOptions, OCObserveAction observeAction,
OCObservationId observeID);
// resource query send by client
char query[MAX_QUERY_LENGTH];
// reqJSON is retrieved from the payload of the received request PDU
- char reqJSONPayload[MAX_REQUEST_LENGTH];
+ uint8_t payload[MAX_REQUEST_LENGTH];
// qos is indicating if the request is CON or NON
OCQualityOfService qos;
// An array of the received vendor specific header options
CAToken_t token, uint8_t tokenLength);
#ifdef WITH_PRESENCE
-/**
- * The OCPresenceTrigger enum delineates the three spec-compliant modes for
- * "Trigger." These enum values are then mapped to JSON strings
- * "create", "change", "delete", respectively, before getting encoded into
- * the JSON payload.
- *
- * @enum OC_PRESENCE_TRIGGER_CREATE The creation of a resource is associated with
- * this invocation of @ref SendPresenceNotification.
- * @enum OC_PRESENCE_TRIGGER_CHANGE The change/update of a resource is associated
- * this invocation of @ref SendPresenceNotification.
- * @enum OC_PRESENCE_TRIGGER_DELETE The deletion of a resource is associated with
- * this invocation of @ref SendPresenceNotification.
- *
- */
-typedef enum
-{
- OC_PRESENCE_TRIGGER_CREATE = 0,
- OC_PRESENCE_TRIGGER_CHANGE = 1,
- OC_PRESENCE_TRIGGER_DELETE = 2
-} OCPresenceTrigger;
/**
* Notify Presence subscribers that a resource has been modified.
--- /dev/null
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OCPAYLOAD_H_
+#define OCPAYLOAD_H_
+
+#include <stdbool.h>
+#include <inttypes.h>
+#include "logger.h"
+#include "octypes.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+typedef struct OCResource OCResource;
+
+#ifdef TB_LOG
+ #define OC_LOG_PAYLOAD(level, tag, payload) OCPayloadLog((level),(tag),(payload))
+ #define UUID_SIZE (16)
+ #define UUID_LENGTH (37)
+const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
+OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
+
+static inline void OCPayloadLogRep(LogLevel level, const char* tag, OCRepPayload* payload)
+{
+ OC_LOG(level, tag, PCF("Payload Type: Representation"));
+ OCRepPayload* rep = payload;
+ int i = 1;
+ while(rep)
+ {
+ OC_LOG_V(level, tag, "\tResource #%d", i);
+ OC_LOG_V(level, tag, "\tURL:%s", rep->uri);
+ OC_LOG(level, tag, PCF("\tResource Types:"));
+ OCStringLL* strll = rep->types;
+ while(strll)
+ {
+ OC_LOG_V(level, tag, "\t\t%s", strll->value);
+ strll = strll->next;
+ }
+ OC_LOG(level, tag, PCF("\tInterfaces:"));
+ strll = rep->interfaces;
+ while(strll)
+ {
+ OC_LOG_V(level, tag, "\t\t%s", strll->value);
+ strll = strll->next;
+ }
+
+ // TODO Finish Logging: Values
+ OCRepPayloadValue* val = rep->values;
+
+ OC_LOG(level, tag, PCF("\tValues:"));
+
+ while(val)
+ {
+ switch(val->type)
+ {
+ case OCREP_PROP_NULL:
+ OC_LOG_V(level, tag, "\t\t%s: NULL", val->name);
+ break;
+ case OCREP_PROP_INT:
+ OC_LOG_V(level, tag, "\t\t%s(int):%lld", val->name, val->i);
+ break;
+ case OCREP_PROP_DOUBLE:
+ OC_LOG_V(level, tag, "\t\t%s(double):%f", val->name, val->d);
+ break;
+ case OCREP_PROP_BOOL:
+ OC_LOG_V(level, tag, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
+ break;
+ case OCREP_PROP_STRING:
+ OC_LOG_V(level, tag, "\t\t%s(string):%s", val->name, val->str);
+ break;
+ case OCREP_PROP_OBJECT:
+ // Note: Only prints the URI (if available), to print further, you'll
+ // need to dig into the object better!
+ OC_LOG_V(level, tag, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
+ break;
+ case OCREP_PROP_ARRAY:
+ switch(val->arr.type)
+ {
+ case OCREP_PROP_INT:
+ OC_LOG_V(level, tag, "\t\t%s(int array):%lld x %lld x %lld",
+ val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_DOUBLE:
+ OC_LOG_V(level, tag, "\t\t%s(double array):%lld x %lld x %lld",
+ val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_BOOL:
+ OC_LOG_V(level, tag, "\t\t%s(bool array):%lld x %lld x %lld",
+ val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_STRING:
+ OC_LOG_V(level, tag, "\t\t%s(string array):%lld x %lld x %lld",
+ val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_OBJECT:
+ OC_LOG_V(level, tag, "\t\t%s(OCRep array):%lld x %lld x %lld",
+ val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ default:
+ OC_LOG_V(ERROR, tag, "\t\t%s <-- Unknown/unsupported array type!",
+ val->name);
+ break;
+ }
+ break;
+ default:
+ OC_LOG_V(ERROR, tag, "\t\t%s <-- Unknown type!", val->name);
+ break;
+ }
+ val = val -> next;
+ }
+
+ ++i;
+ rep = rep->next;
+ }
+
+}
+
+static inline void OCPayloadLogDiscovery(LogLevel level, const char* tag,
+ OCDiscoveryPayload* payload)
+{
+ OC_LOG(level, tag, PCF("Payload Type: Discovery"));
+ int i = 1;
+
+ if(!payload->resources)
+ {
+ OC_LOG(level, tag, PCF("\tNO Resources"));
+ return;
+ }
+
+ OCResourcePayload* res = payload->resources;
+
+ while(res)
+ {
+ OC_LOG_V(level, tag, "\tResource #%d", i);
+ OC_LOG_V(level, tag, "\tURI:%s", res->uri);
+ OC_LOG(level, tag, PCF("\tSID:"));
+ OC_LOG_BUFFER(level, tag, res->sid, UUID_SIZE);
+ OC_LOG(level, tag, PCF("\tResource Types:"));
+ OCStringLL* strll = res->types;
+ while(strll)
+ {
+ OC_LOG_V(level, tag, "\t\t%s", strll->value);
+ strll = strll->next;
+ }
+ OC_LOG(level, tag, PCF("\tInterfaces:"));
+ strll = res->interfaces;
+ while(strll)
+ {
+ OC_LOG_V(level, tag, "\t\t%s", strll->value);
+ strll = strll->next;
+ }
+
+ OC_LOG_V(level, tag, "\tBitmap: %u", res->bitmap);
+ OC_LOG_V(level, tag, "\tSecure?: %s", res->secure ? "true" : "false");
+ OC_LOG_V(level, tag, "\tPort: %u", res->port);
+ OC_LOG(level, tag, PCF(""));
+ res = res->next;
+ ++i;
+ }
+}
+
+static inline void OCPayloadLogDevice(LogLevel level, const char* tag, OCDevicePayload* payload)
+{
+ OC_LOG(level, tag, PCF("Payload Type: Device"));
+ OC_LOG_V(level, tag, "\tURI:%s", payload->uri);
+ OC_LOG(level, tag, PCF("\tSID:"));
+ OC_LOG_BUFFER(level, tag, payload->sid, UUID_SIZE);
+ OC_LOG_V(level, tag, "\tDevice Name:%s", payload->deviceName);
+ OC_LOG_V(level, tag, "\tSpec Version%s", payload->specVersion);
+ OC_LOG_V(level, tag, "\tData Model Version:%s", payload->dataModelVersion);
+}
+
+static inline void OCPayloadLogPlatform(LogLevel level, const char* tag, OCPlatformPayload* payload)
+{
+ OC_LOG(level, tag, PCF("Payload Type: Platform"));
+ OC_LOG_V(level, tag, "\tURI:%s", payload->uri);
+ OC_LOG_V(level, tag, "\tPlatform ID:%s", payload->info.platformID);
+ OC_LOG_V(level, tag, "\tMfg Name:%s", payload->info.manufacturerName);
+ OC_LOG_V(level, tag, "\tMfg URL:%s", payload->info.manufacturerUrl);
+ OC_LOG_V(level, tag, "\tModel Number:%s", payload->info.modelNumber);
+ OC_LOG_V(level, tag, "\tDate of Mfg:%s", payload->info.dateOfManufacture);
+ OC_LOG_V(level, tag, "\tPlatform Version:%s", payload->info.platformVersion);
+ OC_LOG_V(level, tag, "\tOS Version:%s", payload->info.operatingSystemVersion);
+ OC_LOG_V(level, tag, "\tHardware Version:%s", payload->info.hardwareVersion);
+ OC_LOG_V(level, tag, "\tFirmware Version:%s", payload->info.firmwareVersion);
+ OC_LOG_V(level, tag, "\tSupport URL:%s", payload->info.supportUrl);
+ OC_LOG_V(level, tag, "\tSystem Time:%s", payload->info.systemTime);
+}
+
+static inline void OCPayloadLogPresence(LogLevel level, const char* tag, OCPresencePayload* payload)
+{
+ OC_LOG(level, tag, PCF("Payload Type: Presence"));
+ OC_LOG_V(level, tag, "\tSequence Number:%u", payload->sequenceNumber);
+ OC_LOG_V(level, tag, "\tMax Age:%d", payload->maxAge);
+ OC_LOG_V(level, tag, "\tTrigger:%s", convertTriggerEnumToString(payload->trigger));
+ OC_LOG_V(level, tag, "\tResource Type:%s", payload->resourceType);
+}
+
+static inline void OCPayloadLogSecurity(LogLevel level, const char* tag,
+ OCSecurityPayload* payload)
+{
+ OC_LOG(level, tag, PCF("Payload Type: Security"));
+ OC_LOG_V(level, tag, "\tSecurity Data: %s", payload->securityData);
+}
+
+static inline void OCPayloadLog(LogLevel level, const char* tag, OCPayload* payload)
+{
+ if(!payload)
+ {
+ OC_LOG(level, tag, PCF("NULL Payload"));
+ return;
+ }
+ switch(payload->type)
+ {
+ case PAYLOAD_TYPE_REPRESENTATION:
+ OCPayloadLogRep(level, tag, (OCRepPayload*)payload);
+ break;
+ case PAYLOAD_TYPE_DISCOVERY:
+ OCPayloadLogDiscovery(level, tag, (OCDiscoveryPayload*)payload);
+ break;
+ case PAYLOAD_TYPE_DEVICE:
+ OCPayloadLogDevice(level, tag, (OCDevicePayload*)payload);
+ break;
+ case PAYLOAD_TYPE_PLATFORM:
+ OCPayloadLogPlatform(level, tag, (OCPlatformPayload*)payload);
+ break;
+ case PAYLOAD_TYPE_PRESENCE:
+ OCPayloadLogPresence(level, tag, (OCPresencePayload*)payload);
+ break;
+ case PAYLOAD_TYPE_SECURITY:
+ OCPayloadLogSecurity(level, tag, (OCSecurityPayload*)payload);
+ break;
+ default:
+ OC_LOG_V(level, tag, "Unknown Payload Type: %d", payload->type);
+ break;
+ }
+}
+#else
+ #define OC_LOG_PAYLOAD(level, tag, payload)
+#endif
+
+void OCPayloadDestroy(OCPayload* payload);
+
+// Representation Payload
+OCRepPayload* OCRepPayloadCreate();
+
+size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+OCRepPayload* OCRepPayloadClone(const OCRepPayload* payload);
+
+void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child);
+
+bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri);
+
+bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType);
+bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface);
+
+bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType);
+bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface);
+
+bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name);
+bool OCRepPayloadSetNull(OCRepPayload* payload, const char* name);
+
+bool OCRepPayloadSetPropInt(OCRepPayload* payload, const char* name, int64_t value);
+bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64_t* value);
+
+bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
+bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
+
+bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
+bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
+bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, const char** value);
+
+bool OCRepPayloadSetPropBool(OCRepPayload* payload, const char* name, bool value);
+bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool* value);
+
+bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value);
+bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name,
+ OCRepPayload* value);
+bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
+
+bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
+ int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
+ const int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
+ int64_t** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
+ double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
+ const double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
+ double** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
+ char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
+ const char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
+ char*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
+ bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
+ const bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
+ bool** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* name,
+ OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
+ const OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* name,
+ OCRepPayload*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+void OCRepPayloadDestroy(OCRepPayload* payload);
+
+// Discovery Payload
+OCDiscoveryPayload* OCDiscoveryPayloadCreate();
+
+OCSecurityPayload* OCSecurityPayloadCreate(char* securityData);
+void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
+
+void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+ uint16_t port);
+void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res);
+size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload);
+OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index);
+
+void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
+
+// Device Payload
+OCDevicePayload* OCDevicePayloadCreate(const char* uri, const uint8_t* sid, const char* dname,
+ const char* specVer, const char* dmVer);
+void OCDevicePayloadDestroy(OCDevicePayload* payload);
+
+// Platform Payload
+OCPlatformPayload* OCPlatformPayloadCreate(const char* uri, const OCPlatformInfo* platformInfo);
+OCPlatformPayload* OCPlatformPayloadCreateAsOwner(char* uri, OCPlatformInfo* platformInfo);
+
+void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
+
+// Presence Payload
+OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
+ OCPresenceTrigger trigger, const char* resourceType);
+void OCPresencePayloadDestroy(OCPresencePayload* payload);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
--- /dev/null
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OCPRESENCE_H_
+#define OCPRESENCE_H_
+
+#ifdef WITH_PRESENCE
+/**
+ * The OCPresenceTrigger enum delineates the three spec-compliant modes for
+ * "Trigger." These enum values are then mapped to strings
+ * "create", "change", "delete", respectively, before getting encoded into
+ * the payload payload.
+ *
+ * @enum OC_PRESENCE_TRIGGER_CREATE The creation of a resource is associated with
+ * this invocation of @ref SendPresenceNotification.
+ * @enum OC_PRESENCE_TRIGGER_CHANGE The change/update of a resource is associated
+ * this invocation of @ref SendPresenceNotification.
+ * @enum OC_PRESENCE_TRIGGER_DELETE The deletion of a resource is associated with
+ * this invocation of @ref SendPresenceNotification.
+ *
+ */
+typedef enum
+{
+ OC_PRESENCE_TRIGGER_CREATE = 0,
+ OC_PRESENCE_TRIGGER_CHANGE = 1,
+ OC_PRESENCE_TRIGGER_DELETE = 2
+} OCPresenceTrigger;
+#endif
+
+#endif
OCMethod method,
const char *requestUri,
const OCDevAddr *destination,
- const char *request,
+ OCPayload* payload,
OCConnectivityType connectivityType,
OCQualityOfService qos,
OCCallbackData *cbData,
* @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 payload OCRepresentationPayload object representing the 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
OCNotifyListOfObservers (OCResourceHandle handle,
OCObservationId *obsIdList,
uint8_t numberOfIds,
- const char *notificationJSONPayload,
+ const OCRepPayload *payload,
OCQualityOfService qos);
* They have a combined size of 10 bytes.
*/
#ifdef WITH_ARDUINO
-#define MAX_RESPONSE_LENGTH (246)
+#define MAX_RESPONSE_LENGTH (256)
#else
-#define MAX_RESPONSE_LENGTH (1014)
+#define MAX_RESPONSE_LENGTH (1024)
#endif
/**
#define OCTYPES_H_
#include "ocstackconfig.h"
-
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
#ifdef __cplusplus
#include <string.h>
extern "C" {
#endif // __cplusplus
#define WITH_PRESENCE
+#include "ocpresence.h"
//-----------------------------------------------------------------------------
// Defines
//-----------------------------------------------------------------------------
-#define OC_WELL_KNOWN_QUERY "/oic/res"
-#define OC_MULTICAST_DISCOVERY_URI "/oic/res"
+/**
+ * OIC Virtual resources supported by every OIC device.
+ */
+#define OC_RSRVD_WELL_KNOWN_URI "/oic/res"
+#define OC_RSRVD_DEVICE_URI "/oic/d"
+#define OC_RSRVD_PLATFORM_URI "/oic/p"
+#define OC_RSRVD_RESOURCE_TYPES_URI "/oic/res/types/d"
#ifdef WITH_PRESENCE
+#define OC_RSRVD_PRESENCE_URI "/oic/ad"
#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
///Separtor for multiple query string
/**
* Attributes used to form a proper OIC conforming JSON message.
*/
-#define OC_RSRVD_OC "oic"
+//#define OC_RSRVD_OC "oic"
#define OC_RSRVD_PAYLOAD "payload"
#define OC_RSRVD_HREF "href"
#define OC_RSRVD_PROPERTY "prop"
#define OC_RSRVD_TTL "ttl"
#define OC_RSRVD_NONCE "non"
#define OC_RSRVD_TRIGGER "trg"
+#define OC_RSRVD_LINKS "links"
#define OC_RSRVD_INTERFACE_DEFAULT "oic.if.baseline"
#define OC_RSRVD_INTERFACE_LL "oic.if.ll"
// These provide backward compatibility - their use is deprecated
#ifndef GOING_AWAY
#define OC_MULTICAST_PREFIX "224.0.1.187:5683"
-#define OC_MULTICAST_IP "224.0.1.187:5683"
+#define OC_MULTICAST_IP "224.0.1.187"
#define OC_MULTICAST_PORT 5683
#endif // GOING_AWAY
} OCConnectivityType;
/**
- * OC Virtual resources supported by every OC device.
- */
-typedef enum
-{
- OC_WELL_KNOWN_URI= 0, ///< "/oic/res"
- OC_DEVICE_URI, ///< "/oic/d"
- OC_PLATFORM_URI, ///< "/oic/p"
- OC_RESOURCE_TYPES_URI, ///< "/oic/res/d/type"
- #ifdef WITH_PRESENCE
- OC_PRESENCE, ///< "/oic/ad"
- #endif
- OC_MAX_VIRTUAL_RESOURCES ///<s Max items in the list
-} OCVirtualResources;
-
-/**
* OCDoResource methods
*/
typedef enum
} OCHeaderOption;
/**
+ * 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;
+
+/**
+ * This structure is expected as input for device properties.
+ * device name is mandatory and expected from the application.
+ * device id of type UUID will be generated by the stack.
+ */
+typedef struct
+{
+ char *deviceName;
+
+} OCDeviceInfo;
+
+// Enum to describe the type of object held by the OCPayload object
+typedef enum
+{
+ PAYLOAD_TYPE_INVALID,
+ PAYLOAD_TYPE_DISCOVERY,
+ PAYLOAD_TYPE_DEVICE,
+ PAYLOAD_TYPE_PLATFORM,
+ PAYLOAD_TYPE_REPRESENTATION,
+ PAYLOAD_TYPE_SECURITY,
+ PAYLOAD_TYPE_PRESENCE
+} OCPayloadType;
+
+typedef struct
+{
+ // The type of message that was received
+ OCPayloadType type;
+} OCPayload;
+
+typedef enum
+{
+ OCREP_PROP_NULL,
+ OCREP_PROP_INT,
+ OCREP_PROP_DOUBLE,
+ OCREP_PROP_BOOL,
+ OCREP_PROP_STRING,
+ OCREP_PROP_OBJECT,
+ OCREP_PROP_ARRAY
+}OCRepPayloadPropType;
+
+#define MAX_REP_ARRAY_DEPTH 3
+typedef struct
+{
+ OCRepPayloadPropType type;
+ size_t dimensions[MAX_REP_ARRAY_DEPTH];
+
+ union
+ {
+ int64_t* iArray;
+ double* dArray;
+ bool* bArray;
+ char** strArray;
+ struct OCRepPayload** objArray;
+ };
+} OCRepPayloadValueArray;
+
+typedef struct OCRepPayloadValue
+{
+ char* name;
+ OCRepPayloadPropType type;
+ union
+ {
+ int64_t i;
+ double d;
+ bool b;
+ char* str;
+ struct OCRepPayload* obj;
+ OCRepPayloadValueArray arr;
+ };
+ struct OCRepPayloadValue* next;
+
+} OCRepPayloadValue;
+
+typedef struct OCStringLL
+{
+ struct OCStringLL *next;
+ char* value;
+} OCStringLL;
+
+// used for get/set/put/observe/etc representations
+typedef struct OCRepPayload
+{
+ OCPayload base;
+ char* uri;
+ OCStringLL* types;
+ OCStringLL* interfaces;
+ OCRepPayloadValue* values;
+ struct OCRepPayload* next;
+} OCRepPayload;
+
+// used inside a discovery payload
+typedef struct OCResourcePayload
+{
+ char* uri;
+ uint8_t* sid;
+ OCStringLL* types;
+ OCStringLL* interfaces;
+ uint8_t bitmap;
+ bool secure;
+ uint16_t port;
+ struct OCResourcePayload* next;
+} OCResourcePayload;
+
+typedef struct
+{
+ OCPayload base;
+ OCResourcePayload* resources;
+} OCDiscoveryPayload;
+
+typedef struct
+{
+ OCPayload base;
+ char* uri;
+ uint8_t* sid;
+ char* deviceName;
+ char* specVersion;
+ char* dataModelVersion;
+} OCDevicePayload;
+
+typedef struct
+{
+ OCPayload base;
+ char* uri;
+ OCPlatformInfo info;
+} OCPlatformPayload;
+
+typedef struct
+{
+ OCPayload base;
+ char* securityData;
+} OCSecurityPayload;
+#ifdef WITH_PRESENCE
+typedef struct
+{
+ OCPayload base;
+ uint32_t sequenceNumber;
+ uint32_t maxAge;
+ OCPresenceTrigger trigger;
+ char* resourceType;
+} OCPresencePayload;
+#endif
+
+/**
* 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
// 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;
+ // the payload from the request PDU
+ OCPayload *payload;
} OCEntityHandlerRequest;
/**
uint32_t sequenceNumber;
/// resourceURI
const char * resourceUri;
- /// resJSONPayload is retrieved from the payload of the received request PDU
- const char * resJSONPayload;
+ // the payload for the response PDU
+ OCPayload *payload;
/// 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;
-
-/**
- * This structure is expected as input for device properties.
- * device name is mandatory and expected from the application.
- * device id of type UUID will be generated by the stack.
- */
-typedef struct
-{
- char *deviceName;
-
-} OCDeviceInfo;
-
typedef struct
{
// Request handle is passed to server via the entity handler for each incoming request.
// 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;
+ OCPayload* payload;
// An array of the vendor specific header options the entity handler wishes to use in response
uint8_t numSendVendorSpecificHeaderOptions;
OCHeaderOption sendVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
#include "logger.h"
#include "ocstack.h"
+#include "ocpayload.h"
#include <string.h>
#ifdef ARDUINOWIFI
static LightResource Light;
-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
{
OCEntityHandlerResult ehRet = OC_EH_OK;
OCEntityHandlerResponse response = {0};
- char payload[MAX_RESPONSE_LENGTH] = {0};
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if(!payload)
+ {
+ OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+ return OC_EH_ERROR;
+ }
if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
{
if(OC_REST_GET == entityHandlerRequest->method)
{
- size_t responsePayloadGetLength = strlen(responsePayloadGet);
- if (responsePayloadGetLength < (sizeof(payload) - 1))
- {
- strncpy(payload, responsePayloadGet, responsePayloadGetLength);
- }
- else
- {
- ehRet = OC_EH_ERROR;
- }
+ OCRepPayloadSetUri(payload, "/a/light");
+ OCRepPayloadSetPropBool(payload, "state", true);
+ OCRepPayloadSetPropInt(payload, "power", 10);
}
else if(OC_REST_PUT == entityHandlerRequest->method)
{
//Do something with the 'put' payload
- size_t responsePayloadPutLength = strlen(responsePayloadPut);
- if (responsePayloadPutLength < (sizeof(payload) - 1))
- {
- strncpy((char *)payload, responsePayloadPut, responsePayloadPutLength);
- }
- else
- {
- ehRet = OC_EH_ERROR;
- }
+ OCRepPayloadSetUri(payload, "/a/light");
+ OCRepPayloadSetPropBool(payload, "state", false);
+ OCRepPayloadSetPropInt(payload, "power", 0);
}
if (ehRet == OC_EH_OK)
response.requestHandle = entityHandlerRequest->requestHandle;
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = ehRet;
- response.payload = payload;
- response.payloadSize = strlen(payload);
+ response.payload = (OCPayload*) payload;
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions, 0,
sizeof response.sendVendorSpecificHeaderOptions);
#include "ocstack.h"
#include "logger.h"
#include "occlient.h"
+#include "ocpayload.h"
+// Tracking user input
static int UNICAST_DISCOVERY = 0;
static int TEST_CASE = 0;
+static int CONNECTIVITY = 0;
-static const char * UNICAST_DEVICE_DISCOVERY_QUERY = "coap://%s:6298/oic/d";
+static const char * UNICAST_DEVICE_DISCOVERY_QUERY = "coap://%s/oic/d";
static const char * MULTICAST_DEVICE_DISCOVERY_QUERY = "/oic/d";
-static const char * UNICAST_PLATFORM_DISCOVERY_QUERY = "coap://%s:6298/oic/p";
+static const char * UNICAST_PLATFORM_DISCOVERY_QUERY = "coap://%s/oic/p";
static const char * MULTICAST_PLATFORM_DISCOVERY_QUERY = "/oic/p";
-static const char * UNICAST_RESOURCE_DISCOVERY_QUERY = "coap://%s:6298/oic/res";
+static const char * UNICAST_RESOURCE_DISCOVERY_QUERY = "coap://%s/oic/res";
static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
//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 = CT_ADAPTER_IP;
-static std::string putPayload = "{\"oic\":[{\"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;
+// Size to hold IPV4_ADDRESS:PORT
+static const int IPV4_ADDR_SIZE = 24;
//Use ipv4addr for both InitDiscovery and InitPlatformOrDeviceDiscovery
char ipv4addr[IPV4_ADDR_SIZE];
void StripNewLineChar(char* str);
}
}
+OCPayload* putPayload()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+
+ if(!payload)
+ {
+ std::cout << "Failed to create put payload object"<<std::endl;
+ std::exit(1);
+ }
+
+ OCRepPayloadSetPropInt(payload, "power", 15);
+ OCRepPayloadSetPropBool(payload, "state", true);
+
+ return (OCPayload*) payload;
+}
+
static void PrintUsage()
{
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, "-c 0 : Use Default connectivity(IP)");
+ OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
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 Get Request"
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 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");
cbData.cd = NULL;
ret = OCDoResource(&handle, method, query.str().c_str(), 0,
- (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
+ (method == OC_REST_PUT) ? putPayload() : NULL,
(OC_CONNTYPE), qos, &cbData, options, numOptions);
if (ret != OC_STACK_OK)
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_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Put Response"));
}
else
{
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_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Post Response"));
}
else
{
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_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Delete Response"));
}
else
{
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);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Get Response"));
- if(clientResponse->rcvdVendorSpecificHeaderOptions &&
- clientResponse->numRcvdVendorSpecificHeaderOptions)
+ if(clientResponse->numRcvdVendorSpecificHeaderOptions > 0)
{
OC_LOG (INFO, TAG, "Received vendor specific options");
uint8_t i = 0;
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_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Obs Response"));
gNumObserveNotifies++;
if (gNumObserveNotifies == 15) //large number to test observing in DELETE case.
{
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_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Presence Response"));
gNumPresenceNotifies++;
if (gNumPresenceNotifies == 20)
{
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 @ %s:%d",
- clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ "Device =============> Discovered @ %s:%d",
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_CONNTYPE = clientResponse->connType;
parseClientResponse(clientResponse);
switch(TEST_CASE)
if(clientResponse)
{
- //OC_LOG truncates the response as it is too long.
- fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
- fflush(stderr);
+ OC_LOG(INFO, TAG, PCF("Discovery Response:"));
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
}
else
{
if(clientResponse)
{
- //OC_LOG truncates the response as it is too long.
- fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
- fflush(stderr);
+ OC_LOG(INFO, TAG, PCF("Discovery Response:"));
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
}
else
{
OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
std::ostringstream query;
std::ostringstream querySuffix;
- query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
+ query << "coap://" << coapServerIP << ":" << coapServerPort << OC_RSRVD_PRESENCE_URI;
if(TEST_CASE == TEST_OBS_PRESENCE)
{
result = InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS,
{
std::ostringstream multicastPresenceQuery;
multicastPresenceQuery.str("");
- multicastPresenceQuery << "coap://" << OC_MULTICAST_PREFIX << OC_PRESENCE_URI;
+ multicastPresenceQuery << "coap://" << OC_MULTICAST_PREFIX << OC_RSRVD_PRESENCE_URI;
result = InvokeOCDoResource(multicastPresenceQuery, OC_REST_PRESENCE, OC_LOW_QOS,
presenceCB, NULL, 0);
}
}
else
{
- ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
- (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
+
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
+ (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
}
if (ret != OC_STACK_OK)
}
else
{
- ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
- (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
+ (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
}
if (ret != OC_STACK_OK)
}
else
{
- ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
- (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
+ (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
}
if (ret != OC_STACK_OK)
{
TEST_CASE = atoi(optarg);
break;
case 'c':
- OC_CONNTYPE = CT_ADAPTER_IP;
+ CONNECTIVITY = atoi(optarg);
break;
default:
PrintUsage();
}
if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
- (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
+ (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
+ (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
{
PrintUsage();
return -1;
OC_LOG(ERROR, TAG, "OCStack init error");
return 0;
}
+
+ if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP)
+ {
+ OC_CONNTYPE = CT_ADAPTER_IP;
+ }
+ else
+ {
+ OC_LOG(INFO, TAG, "Default Connectivity type selected...");
+ PrintUsage();
+ }
+
if (UNICAST_DISCOVERY)
{
- printf("Enter IPv4 address of the Server hosting resource (Ex: 192.168.0.15)\n");
+ OC_LOG(INFO, TAG, "Enter IP address with port number of the Server hosting resource");
+ OC_LOG(INFO, TAG, "as follows - eg: 192.168.0.15:45454 (IP:Port) \n");
+
if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
{
//Strip newline char from ipv4addr
OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
return OC_STACK_INVALID_PARAM;
}
- }
+ }
if(UNICAST_DISCOVERY == 0 && TEST_CASE == TEST_DISCOVER_DEV_REQ)
{
case CT_ADAPTER_IP:
return "IP";
+ case CT_IP_USE_V4:
+ return "IPv4";
+
+ case CT_IP_USE_V6:
+ return "IPv6";
+
case CT_ADAPTER_GATT_BTLE:
return "GATT";
//-----------------------------------------------------------------------------
/**
- * List of methods that can be inititated from the client
+ * List of methods that can be initiated from the client
*/
typedef enum {
TEST_DISCOVER_REQ = 1,
MAX_TESTS
} CLIENT_TEST;
+/**
+ * List of connectivity types that can be initiated from the client
+ * Required for user input validation
+ */
+typedef enum {
+ CT_ADAPTER_DEFAULT = 0,
+ CT_IP,
+ MAX_CT
+} CLIENT_CONNECTIVITY_TYPE;
+
#ifdef WITH_PRESENCE
int InitPresence();
#endif
#include <unistd.h>
#include <stdint.h>
#include <sstream>
+#include <iostream>
#include "ocstack.h"
#include "logger.h"
#include "occlientbasicops.h"
-#include "cJSON.h"
+#include "ocpayload.h"
#include "oic_malloc.h"
#include "oic_string.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 IPV4_ADDR_SIZE = 24;
static int UNICAST_DISCOVERY = 0;
static int TEST_CASE = 0;
+static int CONNECTIVITY = 0;
-static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oic/res";
-static std::string putPayload = "{\"oic\":[{\"rep\":{\"power\":15,\"state\":true}}]}";
+static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
//The following variable determines the interface protocol (IP, etc)
//to be used for sending unicast messages. Default set to IP.
}
}
+OCPayload* putPayload()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+
+ if(!payload)
+ {
+ std::cout << "Failed to create put payload object"<<std::endl;
+ std::exit(1);
+ }
+
+ OCRepPayloadSetPropInt(payload, "power", 15);
+ OCRepPayloadSetPropBool(payload, "state", true);
+
+ return (OCPayload*) payload;
+}
+
static void PrintUsage()
{
OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
" 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, "-c <0|1> : IPv4/IPv6 (IPv6 not currently supported)");
- OC_LOG(INFO, TAG, "Default connectivityType IPv4");
+ OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
+ OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
}
/*
cbData.cd = NULL;
ret = OCDoResource(NULL, method, query.str().c_str(), 0,
- (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
+ (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
connType, qos, &cbData, options, numOptions);
if (ret != OC_STACK_OK)
if(clientResponse)
{
- OC_LOG_V(INFO, TAG,"PUT Response: %s \nFrom %s:%d\n",
- clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Put Response"));
}
else
{
if(clientResponse)
{
- OC_LOG_V(INFO, TAG,"POST Response: %s \nFrom %s:%d\n",
- clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Post Response"));
}
else
{
if (clientResponse)
{
- OC_LOG_V(INFO, TAG,"Get Response: %s \nFrom %s:%d\n",
- clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+ OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Get Response"));
- if (clientResponse->rcvdVendorSpecificHeaderOptions
- && clientResponse->numRcvdVendorSpecificHeaderOptions)
+ if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
{
OC_LOG (INFO, TAG, "Received vendor specific options");
uint8_t i = 0;
if (clientResponse)
{
OC_LOG_V(INFO, TAG,
- "Device Discovered %s \n @ %s:%d\n",
- clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ "Device =============> Discovered @ %s:%d",
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
collectUniqueResource(clientResponse);
}
if (UNICAST_DISCOVERY)
{
char ipv4addr[IPV4_ADDR_SIZE];
- printf("Enter IPv4 address of the Server hosting "
- "resource (Ex: 192.168.0.15)\n");
+ OC_LOG(INFO, TAG, "Enter IP address with port of the Server hosting resource"\
+ "(Ex: 192.168.0.15:1234) ");
+
if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
{
//Strip newline char from ipv4addr
}
const OCDevAddr *devAddr = &clientResponse->devAddr;
- char *ipaddr = (char *) OICCalloc(1, strlen(devAddr->addr));
+ char *ipaddr = (char *) OICCalloc(1, strlen(devAddr->addr) +1);
if (ipaddr)
{
snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%s", devAddr->addr);
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,"oic");
- 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 *)OICCalloc(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 ** )OICMalloc ((* totalRes) * sizeof(char *))))
- {
- OC_LOG(ERROR, TAG, "Memory not allocated to uri_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 *)OICCalloc(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:
PrintUsage();
break;
}
- printf("\n");
}
void collectUniqueResource(const OCClientResponse * clientResponse)
{
- char * sid = NULL;
- char ** uri = NULL;
- int totalRes = 0;
- int i;
-
- if(parseJSON(clientResponse->resJSONPayload, & sid, & uri, &totalRes)
- != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, "Error while parsing JSON payload in OCClientResponse");
+ OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+ char sidStr[UUID_LENGTH];
- OICFree(sid);
- for (i = 0; i < totalRes; i++)
- {
- OICFree(uri[i]);
- }
- OICFree(uri);
+ while(res) {
- return;
- }
+ int ret = snprintf(sidStr, UUID_LENGTH,
+ "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+ res->sid[0], res->sid[1], res->sid[2], res->sid[3],
+ res->sid[4], res->sid[5], res->sid[6], res->sid[7],
+ res->sid[8], res->sid[9], res->sid[10], res->sid[11],
+ res->sid[12], res->sid[13], res->sid[14], res->sid[15]
+ );
- for(i = 0; i < totalRes; i++)
- {
- if(insertResource(sid, uri[i], clientResponse) == 1)
+ if (ret == UUID_LENGTH - 1)
{
- printf("%s%s%s%s\n",sid, ":", uri[i], " is new");
- printResourceList();
- queryResource();
+ if(insertResource(sidStr, res->uri, clientResponse) == 1)
+ {
+ OC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
+ printResourceList();
+ queryResource();
+ }
+ else {
+ OC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
+ }
}
else
{
- printf("%s%s%s%s\n\n",sid, ":", uri[i], " has been seen before");
+ OC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
}
- }
- OICFree(sid);
- for (i = 0; i < totalRes; i++)
- {
- OICFree(uri[i]);
+ res = res->next;
}
- OICFree(uri);
}
/* This function searches for the resource(sid:uri) in the ResourceList.
{
ResourceNode * iter;
iter = resourceList;
- printf("\nResource List\n");
+ OC_LOG(INFO, TAG, "Resource List: ");
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);
+ OC_LOG(INFO, TAG, "*****************************************************");
+ OC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
+ OC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
+ OC_LOG_V(INFO, TAG, "ip = %s", iter->ip);
+ OC_LOG_V(INFO, TAG, "port = %s", iter->port);
switch (iter->connType & CT_MASK_ADAPTER)
{
case CT_ADAPTER_IP:
- printf("connType = %s\n","IPv4");
+ OC_LOG(INFO, TAG, "connType = Default (IPv4)");
break;
case OC_ADAPTER_GATT_BTLE:
- printf("connType = %s\n","BLE");
+ OC_LOG(INFO, TAG, "connType = BLE");
break;
case OC_ADAPTER_RFCOMM_BTEDR:
- printf("connType = %s\n","BT");
+ OC_LOG(INFO, TAG, "connType = BT");
break;
default:
- printf("connType = %s\n","Invalid connType");
+ OC_LOG(INFO, TAG, "connType = Invalid connType");
break;
}
- printf("*****************************************************\n");
+ OC_LOG(INFO, TAG, "*****************************************************");
iter = iter->next;
}
}
ResourceNode * temp;
while(resourceList)
{
+
temp = resourceList;
resourceList = resourceList->next;
OICFree((void *)temp->sid);
TEST_CASE = atoi(optarg);
break;
case 'c':
- OC_CONNTYPE = CT_ADAPTER_IP;
+
+ CONNECTIVITY = atoi(optarg);
break;
default:
PrintUsage();
}
if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
- (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
+ (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
+ (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
{
PrintUsage();
return -1;
return 0;
}
+ if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP)
+ {
+ OC_CONNTYPE = CT_ADAPTER_IP;//CT_DEFAULT;
+ }
+ else
+ {
+ OC_LOG(INFO, TAG, "Default Connectivity type selected");
+ PrintUsage();
+ }
+
InitDiscovery();
// Break from loop with Ctrl+C
MAX_TESTS
} CLIENT_TEST;
+/**
+ * List of connectivity types that can be initiated from the client
+ * Required for user input validation
+ */
+typedef enum {
+ CT_ADAPTER_DEFAULT = 0,
+ CT_IP,
+ MAX_CT
+} CLIENT_CONNECTIVITY_TYPE;
+
//-----------------------------------------------------------------------------
//ResourceNode
//-----------------------------------------------------------------------------
#include <ocstack.h>
#include <iostream>
#include <sstream>
+#include "ocpayload.h"
#include "logger.h"
const char *getResult(OCStackResult result);
std::string getIPAddrTBServer(OCClientResponse * clientResponse);
std::string getPortTBServer(OCClientResponse * clientResponse);
-std::string getQueryStrForGetPut(const char * responsePayload);
+std::string getQueryStrForGetPut();
#define TAG PCF("occlient")
#define DEFAULT_CONTEXT_VALUE 0x99
MAX_TESTS
} CLIENT_TEST;
+/**
+ * List of connectivity types that can be initiated from the client
+ * Required for user input validation
+ */
+typedef enum {
+ CT_ADAPTER_DEFAULT = 0,
+ CT_IP,
+ MAX_CT
+} CLIENT_CONNECTIVITY_TYPE;
+
unsigned static int TEST = TEST_INVALID;
+unsigned static int CONNECTIVITY = 0;
typedef struct
{
{"?if=oic.if.ll", TEST_PUT_LINK_LIST},
};
-static std::string putPayload = "{\"state\":\"off\",\"power\":\"0\"}";
//The following variable determines the interface protocol (IP, etc)
//to be used for sending unicast messages. Default set to IP.
int InitGetRequest(OCClientResponse * clientResponse);
int InitDiscovery();
+OCPayload* putPayload()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+
+ if(!payload)
+ {
+ std::cout << "Failed to create put payload object"<<std::endl;
+ std::exit(1);
+ }
+
+ OCRepPayloadSetPropInt(payload, "power", 15);
+ OCRepPayloadSetPropBool(payload, "state", true);
+
+ return (OCPayload*) payload;
+}
+
void PrintUsage()
{
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, "-c 0 : Default auto-selection");
+ OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
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 "\
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);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
}
return OC_STACK_KEEP_TRANSACTION;
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);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
}
else
{
OC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d",
gNumObserveNotifies);
- OC_LOG_V(INFO, TAG, "Fnd' Rsrc': %s", clientResponse->resJSONPayload);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);;
gNumObserveNotifies++;
if (gNumObserveNotifies == 3)
{
}
OC_LOG_V(INFO, TAG,
- "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
- clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ "Device =============> Discovered @ %s:%d",
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
if(TEST == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TEST == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\
TEST == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST)
std::ostringstream obsReg;
obsReg << "coap://" << clientResponse->devAddr.addr << ":" <<
clientResponse->devAddr.addr <<
- getQueryStrForGetPut(clientResponse->resJSONPayload);
+ getQueryStrForGetPut();
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());
+ OC_LOG_V(INFO, TAG, "OBSERVE payload from client =");
+ OC_LOG_PAYLOAD(INFO, TAG, putPayload());
ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(), 0, 0, OC_CONNTYPE,
OC_LOW_QOS, &cbData, NULL, 0);
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());
+ OC_LOG_V(INFO, TAG, "PUT payload from client = ");
+ OC_LOG_PAYLOAD(INFO, TAG, putPayload());
- ret = OCDoResource(NULL, OC_REST_PUT, getQuery.str().c_str(), 0, putPayload.c_str(),
+ ret = OCDoResource(NULL, OC_REST_PUT, getQuery.str().c_str(), 0, putPayload(),
OC_CONNTYPE, OC_LOW_QOS, &cbData, NULL, 0);
if (ret != OC_STACK_OK)
{
cbData.cb = discoveryReqCB;
cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
cbData.cd = NULL;
- ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
OC_LOW_QOS,
&cbData, NULL, 0);
if (ret != OC_STACK_OK)
TEST = atoi(optarg);
break;
case 'c':
- OC_CONNTYPE = CT_ADAPTER_IP;
+ CONNECTIVITY = atoi(optarg);
break;
default:
PrintUsage();
return -1;
}
}
- if (TEST <= TEST_INVALID || TEST >= MAX_TESTS)
+ if ((TEST <= TEST_INVALID || TEST >= MAX_TESTS) ||
+ (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
{
PrintUsage();
return -1;
return 0;
}
+ if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP)
+ {
+ OC_CONNTYPE = CT_ADAPTER_IP;
+ }
+ else
+ {
+ OC_LOG(INFO, TAG, "Default Connectivity type selected...");
+ OC_CONNTYPE = CT_ADAPTER_IP;
+ }
+
InitDiscovery();
// Break from loop with Ctrl+C
return 0;
}
-std::string getQueryStrForGetPut(const char * responsePayload)
+std::string getQueryStrForGetPut()
{
-
- std::string jsonPayload(responsePayload);
-
return "/a/room";
}
#include "ocstack.h"
#include "logger.h"
#include "occlientslow.h"
+#include "ocpayload.h"
+// Tracking user input
static int UNICAST_DISCOVERY = 0;
static int TEST_CASE = 0;
-static const char * UNICAST_DISCOVERY_QUERY = "coap://%s:6298/oic/res";
-static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
+static int CONNECTIVITY = 0;
+
+static const char * UNICAST_DISCOVERY_QUERY = "coap://%s/oic/res";
static std::string coapServerIP = "255.255.255.255";
-static std::string coapServerPort = "5683";
+static uint16_t coapServerPort = 5683;
static std::string coapServerResource = "/a/led";
//The following variable determines the interface protocol (IP, etc)
//to be used for sending unicast messages. Default set to IP.
static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
-static int IPV4_ADDR_SIZE = 16;
+static int IPV4_ADDR_SIZE = 24;
void StripNewLineChar(char* str);
int gQuitFlag = 0;
static void PrintUsage()
{
- 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, "Usage : occlient -c <0|1|2> -u <0|1> -t <1|2|3>");
+ OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
+ OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
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");
OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get Request");
+ OC_LOG(INFO, TAG, "-t 4 : Discover Resources and Initiate NonConfirmable Put Request");
+ OC_LOG(INFO, TAG, "-t 5 : Discover Resources and Initiate Confirmable Put Request");
+}
+
+OCPayload* putPayload()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+
+ if(!payload)
+ {
+ std::cout << "Failed to create put payload object"<<std::endl;
+ std::exit(1);
+ }
+
+ OCRepPayloadSetPropInt(payload, "power", 15);
+ OCRepPayloadSetPropBool(payload, "state", true);
+
+ return (OCPayload*) payload;
}
OCStackResult InvokeOCDoResource(std::ostringstream &query,
cbData.cd = NULL;
ret = OCDoResource(NULL, method, query.str().c_str(), 0,
- NULL, OC_CONNTYPE, qos, &cbData, options, numOptions);
+ (method == OC_REST_PUT) ? putPayload() : NULL,
+ OC_CONNTYPE, qos, &cbData, options, numOptions);
if (ret != OC_STACK_OK)
{
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);
+ OC_LOG(INFO, TAG, "Get Response =============> ");
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
if(clientResponse->rcvdVendorSpecificHeaderOptions &&
clientResponse->numRcvdVendorSpecificHeaderOptions)
{
OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
- OC_LOG_V(INFO, TAG,
- "Device =============> Discovered %s @ %s:%d",
- clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ OC_LOG_V(INFO, TAG, "Discovered @ %s:%u =============> ",
+ clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ OC_LOG_PAYLOAD (INFO, TAG, clientResponse->payload);
parseClientResponse(clientResponse);
case TEST_CON_OP:
InitGetRequest(OC_HIGH_QOS);
break;
+ case TEST_NON_CON_PUT:
+ InitPutRequest(OC_LOW_QOS);
+ break;
+ case TEST_CON_PUT:
+ InitPutRequest(OC_HIGH_QOS);
+ break;
default:
PrintUsage();
break;
OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
std::ostringstream query;
query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-
+ OC_LOG_V (INFO, TAG, "Performing GET with 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));
}
+int InitPutRequest(OCQualityOfService qos)
+{
+ OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+ std::ostringstream query;
+ query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+ OC_LOG_V (INFO, TAG, "Performing PUT with query : %s", query.str().c_str());
+ return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)?
+ OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
+}
+
int InitDiscovery()
{
OCStackResult ret;
if (UNICAST_DISCOVERY)
{
char ipv4addr[IPV4_ADDR_SIZE];
- printf("Enter IPv4 address of the Server hosting resource (Ex: 192.168.0.15)\n");
+ OC_LOG(INFO, TAG, "Enter IPv4:port of the Server hosting resource"\
+ "(Ex: 192.168.0.15:1234)");
if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
{
//Strip newline char from ipv4addr
TEST_CASE = atoi(optarg);
break;
case 'c':
- OC_CONNTYPE = CT_ADAPTER_IP;
+ CONNECTIVITY = atoi(optarg);
break;
default:
PrintUsage();
}
if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
- (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
+ (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
+ (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
{
PrintUsage();
return -1;
return 0;
}
+ if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP)
+ {
+ OC_CONNTYPE = CT_ADAPTER_IP;
+ }
+ else
+ {
+ OC_LOG(INFO, TAG, "Default Connectivity type selected...");
+ OC_CONNTYPE = CT_ADAPTER_IP;
+ }
+
InitDiscovery();
// Break from loop with Ctrl+C
TEST_DISCOVER_REQ = 1,
TEST_NON_CON_OP,
TEST_CON_OP,
+ TEST_NON_CON_PUT,
+ TEST_CON_PUT,
MAX_TESTS
} CLIENT_TEST;
+/**
+ * List of connectivity types that can be initiated from the client
+ * Required for user input validation
+ */
+typedef enum {
+ CT_ADAPTER_DEFAULT = 0,
+ CT_IP,
+ MAX_CT
+} CLIENT_CONNECTIVITY_TYPE;
+
//-----------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------
* POST & Discovery operations
*/
int InitGetRequest(OCQualityOfService qos);
+int InitPutRequest(OCQualityOfService qos);
int InitDiscovery();
/* Function to retrieve ip address, port no. of the server
#include <array>
#include "ocstack.h"
#include "logger.h"
-#include "cJSON.h"
+#include "ocpayload.h"
#include "ocserver.h"
//string length of "/a/light/" + std::numeric_limits<int>::digits10 + '\0'"
#define numPresenceResources (2)
#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 responsePayloadDeleteResourceNotSupported[] =
- "{App determines payload: The request is received for a non-support resource.}";
-
-
char *gResourceUri= (char *)"/a/light";
const char *dateOfManufacture = "myDateOfManufacture";
const char *deviceName = "myDeviceName";
OCPlatformInfo platformInfo;
OCDeviceInfo deviceInfo;
+OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if(!payload)
+ {
+ OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+ return nullptr;
+ }
+
+ OCRepPayloadSetUri(payload, uri);
+ OCRepPayloadSetPropBool(payload, "state", state);
+ OCRepPayloadSetPropInt(payload, "power", power);
+
+ return payload;
+}
+
//This function takes the request as an input and returns the response
-//in JSON format.
-char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
{
- cJSON *json = cJSON_CreateObject();
- cJSON *format;
- char *jsonResponse;
+ if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+ OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+ return nullptr;
+ }
+
+ OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
+
LightResource *currLightResource = &Light;
if (ehRequest->resource == gLightInstance[0].handle)
if(OC_REST_PUT == ehRequest->method)
{
- // Get cJSON pointer to query
- cJSON *putJson = cJSON_Parse(ehRequest->reqJSONPayload);
-
- if(!putJson)
+ // Get pointer to query
+ int64_t pow;
+ if(OCRepPayloadGetPropInt(input, "power", &pow))
{
- OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
- return NULL;
+ currLightResource->power =pow;
}
- // Get root of JSON payload, then the 1st resource.
- cJSON* carrier = cJSON_GetObjectItem(putJson, "oic");
- if (carrier)
- {
- 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;
- }
- }
- else
+ bool state;
+ if(OCRepPayloadGetPropBool(input, "state", &state))
{
- OC_LOG_V(WARNING, TAG, "Failed to find oic node");
+ currLightResource->state = state;
}
-
- cJSON_Delete(putJson);
}
- cJSON_AddStringToObject(json,"href",gResourceUri);
- cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
- cJSON_AddBoolToObject(format, "state", currLightResource->state);
- cJSON_AddNumberToObject(format, "power", currLightResource->power);
-
- jsonResponse = cJSON_Print(json);
- cJSON_Delete(json);
-
- return jsonResponse;
+ return getPayload(gResourceUri, currLightResource->power, currLightResource->state);
}
/*
}
OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
- char *payload, uint16_t maxPayloadSize)
+ OCRepPayload **payload)
{
OCEntityHandlerResult ehResult;
bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query);
// Empty payload if the query has no match.
if (queryPassed)
{
- char *getResp = constructJsonResponse(ehRequest);
+ OCRepPayload *getResp = constructResponse(ehRequest);
if(!getResp)
{
- OC_LOG(ERROR, TAG, "constructJsonResponse failed");
+ OC_LOG(ERROR, TAG, "constructResponse 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);
+ *payload = getResp;
+ ehResult = OC_EH_OK;
}
else
{
}
OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
- char *payload, uint16_t maxPayloadSize)
+ OCRepPayload** payload)
{
OCEntityHandlerResult ehResult;
- char *putResp = constructJsonResponse(ehRequest);
+ OCRepPayload *putResp = constructResponse(ehRequest);
if(!putResp)
{
return OC_EH_ERROR;
}
- 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);
+ *payload = putResp;
+ ehResult = OC_EH_OK;
return ehResult;
}
OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
- OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize)
+ OCEntityHandlerResponse *response, OCRepPayload** payload)
{
OCEntityHandlerResult ehResult = OC_EH_OK;
- char *respPLPost_light = NULL;
- cJSON *json;
- cJSON *format;
+ OCRepPayload *respPLPost_light = nullptr;
/*
* The entity handler determines how to process a POST request.
char newLightUri[URI_MAXSIZE];
snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);
- json = cJSON_CreateObject();
- cJSON_AddStringToObject(json,"href",gResourceUri);
- cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
- cJSON_AddStringToObject(format, "createduri", (char *) newLightUri);
+ respPLPost_light = OCRepPayloadCreate();
+ OCRepPayloadSetUri(respPLPost_light, gResourceUri);
+ OCRepPayloadSetPropString(respPLPost_light, "createduri", newLightUri);
if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
{
gLightInstance[gCurrLightInstance].state = 0;
gLightInstance[gCurrLightInstance].power = 0;
gCurrLightInstance++;
- respPLPost_light = cJSON_Print(json);
strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
ehResult = OC_EH_RESOURCE_CREATED;
}
-
- cJSON_Delete(json);
}
else
{
// Update repesentation of /a/light
Light.state = true;
Light.power = 11;
- respPLPost_light = constructJsonResponse(ehRequest);
+ respPLPost_light = constructResponse(ehRequest);
}
}
else
gLightInstance[i].power = 22;
if (i == 0)
{
- respPLPost_light = constructJsonResponse(ehRequest);
+ respPLPost_light = constructResponse(ehRequest);
break;
}
else if (i == 1)
{
- respPLPost_light = constructJsonResponse(ehRequest);
+ respPLPost_light = constructResponse(ehRequest);
}
}
}
}
- if ((respPLPost_light != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_light)))
+ if ((respPLPost_light != NULL))
{
- strncpy(payload, respPLPost_light, strlen((char *)respPLPost_light));
+ *payload = respPLPost_light;
}
else
{
- OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
+ OC_LOG(INFO, TAG, "Payload was NULL");
ehResult = OC_EH_ERROR;
}
- free(respPLPost_light);
return ehResult;
}
-OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest,
- char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
{
if(ehRequest == NULL)
{
* 2. optionally, app removes observers out of its array 'interestedObservers'
*/
- const char* deleteResponse = NULL;
-
if ((ehRequest != NULL) && (ehRequest->resource == Light.handle))
{
//Step 1: Ask stack to do the work.
{
OC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded.");
ehResult = OC_EH_OK;
- deleteResponse = responsePayloadDeleteOk;
//Step 2: clear observers who wanted to observe this resource at the app level.
for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
else if (result == OC_STACK_NO_RESOURCE)
{
OC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted.");
- deleteResponse = responsePayloadResourceDoesNotExist;
ehResult = OC_EH_RESOURCE_DELETED;
}
else
{
OC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource().");
- deleteResponse = responsePayloadDeleteNotOK;
ehResult = OC_EH_ERROR;
}
}
//Let's this app not supporting DELETE on some resources so
//consider the DELETE request is received for a non-support resource.
OC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource.");
- deleteResponse = responsePayloadDeleteResourceNotSupported;
ehResult = OC_EH_FORBIDDEN;
}
- if (maxPayloadSize > strlen ((char *)deleteResponse))
- {
- strncpy(payload, deleteResponse, strlen((char *)deleteResponse));
- }
- else
- {
- OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
- ehResult = OC_EH_ERROR;
- }
-
return ehResult;
}
-OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest,
- char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest)
{
OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
- const char* response = NULL;
- response = responsePayloadResourceDoesNotExist;
-
- if ( (ehRequest != NULL) &&
- (maxPayloadSize > strlen ((char *)response)) )
- {
- strncpy((char *)payload, response, strlen((char *)response));
- }
- else
- {
- OC_LOG_V (ERROR, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
- }
-
return OC_EH_RESOURCE_NOT_FOUND;
}
OCEntityHandlerResult ehResult = OC_EH_OK;
OCEntityHandlerResponse response;
- char payload[MAX_RESPONSE_LENGTH] = {0};
// Validate pointer
if (!entityHandlerRequest)
memset(response.sendVendorSpecificHeaderOptions, 0,
sizeof response.sendVendorSpecificHeaderOptions);
memset(response.resourceUri, 0, sizeof response.resourceUri);
+ OCRepPayload* payload = nullptr;
if (flag & OC_REQUEST_FLAG)
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);
}
else if (OC_REST_GET == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
- ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
}
else if (OC_REST_PUT == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
- ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
}
else if (OC_REST_DELETE == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
- ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessDeleteRequest (entityHandlerRequest);
}
else
{
response.requestHandle = entityHandlerRequest->requestHandle;
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = ehResult;
- response.payload = payload;
- response.payloadSize = strlen(payload);
+ response.payload = reinterpret_cast<OCPayload*>(payload);
// Indicate that response is NOT in a persistent buffer
response.persistentBufferFlag = 0;
OCEntityHandlerResult ehResult = OC_EH_OK;
OCEntityHandlerResponse response;
- char payload[MAX_RESPONSE_LENGTH] = {0};
// Validate pointer
if (!entityHandlerRequest)
memset(response.sendVendorSpecificHeaderOptions,
0, sizeof response.sendVendorSpecificHeaderOptions);
memset(response.resourceUri, 0, sizeof response.resourceUri);
+ OCRepPayload* payload = nullptr;
if (flag & OC_REQUEST_FLAG)
{
if (OC_REST_GET == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
- ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
}
else if (OC_REST_PUT == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
- ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
}
else if (OC_REST_POST == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
- ehResult = ProcessPostRequest (entityHandlerRequest, &response, payload, sizeof(payload) - 1);
+ ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
}
else if (OC_REST_DELETE == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
- ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessDeleteRequest (entityHandlerRequest);
}
else
{
response.requestHandle = entityHandlerRequest->requestHandle;
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = ehResult;
- response.payload = payload;
- response.payloadSize = strlen(payload);
+ response.payload = reinterpret_cast<OCPayload*>(payload);
// Indicate that response is NOT in a persistent buffer
response.persistentBufferFlag = 0;
}
}
+ OCPayloadDestroy(response.payload);
return ehResult;
}
}
}
- cJSON *json = cJSON_CreateObject();
- cJSON *format;
- cJSON_AddStringToObject(json,"href",gResourceUri);
- cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
- cJSON_AddBoolToObject(format, "state", Light.state);
- cJSON_AddNumberToObject(format, "power", Light.power);
-
- char * obsResp = cJSON_Print(json);
- cJSON_Delete(json);
+ OCRepPayload* payload = getPayload(gResourceUri, Light.power, Light.state);
result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
- obsResp, OC_NA_QOS);
- free(obsResp);
+ payload, OC_NA_QOS);
+ OCRepPayloadDestroy(payload);
}
else if (gObserveNotifyType == 0)
{
*/
int createLightResource (char *uri, LightResource *lightResource);
-/* This method converts the payload to JSON format */
-char* constructJsonResponse (OCEntityHandlerRequest *ehRequest);
+/* This method constructs a response from the request */
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
/* This method changes the Light power using an independent thread
* and notifies the observers of new state of the resource.
/* Following methods process the PUT, GET, POST, Delete,
* & Observe requests */
OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- uint16_t maxPayloadSize);
+ OCRepPayload **payload);
OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- uint16_t maxPayloadSize);
+ OCRepPayload **payload);
OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
OCEntityHandlerResponse *response,
- char *payload,
- uint16_t maxPayloadSize);
-OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- uint16_t maxPayloadSize);
-
-OCEntityHandlerResult ProcessNonExistingResourceRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- uint16_t maxPayloadSize);
+ OCRepPayload **payload);
+OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest);
+
+OCEntityHandlerResult ProcessNonExistingResourceRequest (OCEntityHandlerRequest *ehRequest);
void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest);
void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest);
#include <pthread.h>
#include "ocstack.h"
#include "logger.h"
-#include "cJSON.h"
#include "ocserverbasicops.h"
+#include "ocpayload.h"
//string length of "/a/led/" + std::numeric_limits<int>::digits10 + '\0'"
// 7 + 9 + 1 = 17
char *gResourceUri= (char *)"/a/led";
-//This function takes the request as an input and returns the response
-//in JSON format.
-char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
+OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
{
- cJSON *json = cJSON_CreateObject();
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if(!payload)
+ {
+ OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+ return nullptr;
+ }
+
+ OCRepPayloadSetUri(payload, uri);
+ OCRepPayloadSetPropBool(payload, "state", state);
+ OCRepPayloadSetPropInt(payload, "power", power);
- if(!json)
+ return payload;
+}
+
+//This function takes the request as an input and returns the response
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
+{
+ if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
{
- OC_LOG (ERROR, TAG, "json object not created properly");
- return NULL;
+ OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+ return nullptr;
}
- cJSON *format;
- cJSON *putJson = NULL;
- char *jsonResponse = NULL;
+ OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
+
LEDResource *currLEDResource = &LED;
if (ehRequest->resource == gLedInstance[0].handle)
if(OC_REST_PUT == ehRequest->method)
{
- cJSON* jsonObj = NULL;
- putJson = cJSON_Parse(ehRequest->reqJSONPayload);
- if(putJson)
+ // Get pointer to query
+ int64_t pow;
+ if(OCRepPayloadGetPropInt(input, "power", &pow))
{
- jsonObj = cJSON_GetObjectItem(putJson,"oic");
- if (jsonObj)
- {
- jsonObj = cJSON_GetArrayItem(jsonObj, 0);
- if (jsonObj)
- {
- jsonObj = cJSON_GetObjectItem(jsonObj, "rep");
- }
- }
- }
- if (NULL == jsonObj)
- {
- OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
- goto exit;
- }
-
- cJSON* prop = cJSON_GetObjectItem(jsonObj,"power");
- if (prop)
- {
- currLEDResource->power =prop->valueint;
+ currLEDResource->power =pow;
}
- prop = cJSON_GetObjectItem(jsonObj,"state");
- if (prop)
+ bool state;
+ if(OCRepPayloadGetPropBool(input, "state", &state))
{
- currLEDResource->state = prop->valueint;
+ currLEDResource->state = state;
}
}
- cJSON_AddStringToObject(json,"href",gResourceUri);
- format = cJSON_CreateObject();
-
- if(!format)
- {
- OC_LOG (ERROR, TAG, "format object not created properly");
- goto exit;
- }
-
- cJSON_AddItemToObject(json, "rep", format);
- cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
- cJSON_AddNumberToObject(format, "power", currLEDResource->power);
-
- jsonResponse = cJSON_Print(json);
-
-exit:
- cJSON_Delete(putJson);
- cJSON_Delete(json);
- return jsonResponse;
+ return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
}
-OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload,
- uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
+ OCRepPayload **payload)
{
OCEntityHandlerResult ehResult;
- char *getResp = constructJsonResponse(ehRequest);
+ OCRepPayload *getResp = constructResponse(ehRequest);
if(getResp)
{
- 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);
- }
+ *payload = getResp;
+ ehResult = OC_EH_OK;
+ }
else
{
ehResult = OC_EH_ERROR;
return ehResult;
}
-OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload,
- uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
+ OCRepPayload **payload)
{
OCEntityHandlerResult ehResult;
- char *putResp = constructJsonResponse(ehRequest);
+ OCRepPayload *putResp = constructResponse(ehRequest);
if(putResp)
{
- 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);
+ *payload = putResp;
+ ehResult = OC_EH_OK;
}
else
{
return ehResult;
}
-OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload,
- uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
+ OCEntityHandlerResponse *response, OCRepPayload **payload)
{
- char *respPLPost_led = NULL;
- cJSON *json;
- cJSON *format;
- OCEntityHandlerResult ehResult;
+ OCRepPayload *respPLPost_led = nullptr;
+ OCEntityHandlerResult ehResult = OC_EH_OK;
/*
* The entity handler determines how to process a POST request.
char newLedUri[URI_MAXSIZE ];
snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
- json = cJSON_CreateObject();
- if(!json)
- {
- return OC_EH_ERROR;
- }
-
- cJSON_AddStringToObject(json,"href",gResourceUri);
- format = cJSON_CreateObject();
-
- if(!format)
- {
- return OC_EH_ERROR;
- }
-
- cJSON_AddItemToObject(json, "rep", format);
- cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
+ respPLPost_led = OCRepPayloadCreate();
+ OCRepPayloadSetUri(respPLPost_led, gResourceUri);
+ OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
{
gLedInstance[gCurrLedInstance].state = 0;
gLedInstance[gCurrLedInstance].power = 0;
gCurrLedInstance++;
- respPLPost_led = cJSON_Print(json);
+ strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
+ ehResult = OC_EH_RESOURCE_CREATED;
}
-
- cJSON_Delete(json);
}
else
{
- respPLPost_led = constructJsonResponse(ehRequest);
+ respPLPost_led = constructResponse(ehRequest);
}
}
else
{
if (i == 0)
{
- respPLPost_led = constructJsonResponse(ehRequest);
+ respPLPost_led = constructResponse(ehRequest);
break;
}
else if (i == 1)
{
- respPLPost_led = constructJsonResponse(ehRequest);
+ respPLPost_led = constructResponse(ehRequest);
}
}
}
}
- if ((respPLPost_led != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_led)))
+ if ((respPLPost_led != NULL))
{
- strncpy(payload, respPLPost_led, strlen((char *)respPLPost_led));
+ *payload = respPLPost_led;
ehResult = OC_EH_OK;
}
else
{
- OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
+ OC_LOG_V (INFO, TAG, "Payload was NULL");
ehResult = OC_EH_ERROR;
}
- free(respPLPost_led);
-
return ehResult;
}
OCEntityHandlerResult ehResult = OC_EH_ERROR;
OCEntityHandlerResponse response;
- char payload[MAX_RESPONSE_LENGTH] = {0};
+
+ // Validate pointer
+ if (!entityHandlerRequest)
+ {
+ OC_LOG (ERROR, TAG, "Invalid request pointer");
+ return OC_EH_ERROR;
+ }
+
+ OCRepPayload* payload = nullptr;
if (flag & OC_REQUEST_FLAG)
{
if (OC_REST_GET == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
- ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
}
else if (OC_REST_PUT == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
- ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
}
else if (OC_REST_POST == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
- ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
}
else
{
entityHandlerRequest->method);
}
- if (ehResult == OC_EH_OK)
+ if (ehResult == OC_EH_OK && 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 = payload;
- response.payloadSize = strlen(payload);
+ response.payload = reinterpret_cast<OCPayload*>(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
memset(response.resourceUri, 0, sizeof(response.resourceUri));
}
}
}
+
+ OCPayloadDestroy(response.payload);
return ehResult;
}
*/
int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
-/* This method converts the payload to JSON format */
-char* constructJsonResponse (OCEntityHandlerRequest *ehRequest);
+/* This method constructs a response from the request */
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
/* Following methods process the PUT, GET, POST
* requests
*/
OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- uint16_t maxPayloadSize);
+ OCRepPayload **payload);
OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- uint16_t maxPayloadSize);
+ OCRepPayload **payload);
OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- uint16_t maxPayloadSize);
+ OCEntityHandlerResponse *response,
+ OCRepPayload **payload);
/* call getResult in common.cpp to get the result in string format. */
const char *getResult(OCStackResult result);
#include <pthread.h>
#include <ocstack.h>
#include <logger.h>
+#include "ocpayload.h"
const char *getResult(OCStackResult result);
static LightResource light;
-// TODO : hard coded for now, change after Sprint10
-const char rspGetRoomDefault[] = "{\"href\":\"/a/room\",\"rep\":{\"name\":\"John's Room\"}}";
-const char rspGetRoomCollection[] = "{\"href\":\"/a/room\"}";
-// TODO : Needs to be changed to retrieve current status of room and return that in response
-const char rspPutRoomDefault[] = "{\"href\":\"/a/room\",\"rep\":{\"name\":\"John's Room\"}}";
-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 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 rspPutLightCollection[] = "{\"href\":\"/a/light\"}";
-const char rspFailureLight[] = "{\"href\":\"/a/light\",\"rep\":{\"error\":\"LIGHT_OP_FAIL\"}}";
-
-
-// TODO : hard coded for now, change after Sprint4
-const char rspGetFanDefault[] = "{\"href\":\"/a/fan\",\"rep\":{\"state\":\"true\",\"speed\":10}}";
-const char rspGetFanCollection[] = "{\"href\":\"/a/fan\"}";
-// TODO : Needs to be changed to retrieve current status of fan and return that in response
-const char rspPutFanDefault[] = "{\"href\":\"/a/fan\",\"rep\":{\"state\":\"false\",\"speed\":0}}";
-const char rspPutFanCollection[] = "{\"href\":\"/a/fan\"}";
-const char rspFailureFan[] = "{\"href\":\"/a/fan\",\"rep\":{\"error\":\"FAN_OP_FAIL\"}}";
+char *gLightResourceUri= (char *)"/a/light";
+char *gRoomResourceUri= (char *)"/a/room";
+char *gFanResourceUri= (char *)"/a/fan";
typedef enum
{
unsigned static int TEST = TEST_INVALID;
-static OCEntityHandlerResult
-HandleCallback(OCEntityHandlerRequest * ehRequest,
- const char* opStr,
- const char* errStr,
- char *payload,
- uint16_t maxPayloadSize)
-{
- OCEntityHandlerResult ret = OC_EH_OK;
-
- // Append opStr or errStr, after making sure there is
- // enough room in the payload
- if (strlen(opStr) < (maxPayloadSize - strlen(payload)))
- {
- strncat((char*)payload, opStr, strlen(opStr));
- }
- else if (strlen(errStr) < (maxPayloadSize - strlen(payload)))
- {
- strncat((char*)payload, errStr, strlen(errStr));
- ret = OC_EH_ERROR;
- }
- else
- {
- ret = OC_EH_ERROR;
- }
-
- return ret;
-}
-
static void
PrintReceivedMsgInfo(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest)
{
const char* typeOfMessage;
+ const char* typeOfMethod;
switch (flag)
{
typeOfMessage = "UNKNOWN";
}
- OC_LOG_V(INFO, TAG, "Receiving message type: %s, method %s",
- typeOfMessage,
- (ehRequest->method == OC_REST_GET) ? "OC_REST_GET" : "OC_REST_PUT" );
+ if (ehRequest == NULL)
+ {
+ typeOfMethod = "UNKNOWN";
+ }
+ else if (ehRequest->method == OC_REST_GET)
+ {
+ typeOfMethod = "OC_REST_GET";
+ }
+ else
+ {
+ typeOfMethod = "OC_REST_PUT";
+ }
+
+ OC_LOG_V(INFO, TAG, "Receiving message type: %s, method %s", typeOfMessage,
+ typeOfMethod);
}
OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
{
OCEntityHandlerResult ret = OC_EH_OK;
OCEntityHandlerResponse response;
- char payload[MAX_RESPONSE_LENGTH] = {0};
+ OCRepPayload* payload = OCRepPayloadCreate();
OC_LOG_V(INFO, TAG, "Callback for Room");
PrintReceivedMsgInfo(flag, ehRequest );
{
if(query.find(OC_RSRVD_INTERFACE_DEFAULT) != std::string::npos)
{
- 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));
- }
- if(ret != OC_EH_ERROR)
- {
- ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
- ret = HandleCallback(ehRequest,
- rspGetFanCollection, rspFailureFan, payload, sizeof(payload));
- }
+ OCRepPayloadSetUri(payload, gRoomResourceUri);
+ OCRepPayloadSetPropString(payload, "name", "John's Room");
+
+ OCRepPayload *tempPayload = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload, gLightResourceUri);
+ OCRepPayloadAppend(payload, tempPayload);
+
+ OCRepPayload *tempPayload2 = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload2, gFanResourceUri);
+ OCRepPayloadAppend(payload, tempPayload2);
}
else if(query.find(OC_RSRVD_INTERFACE_LL) != std::string::npos)
{
- 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));
- }
- if(ret != OC_EH_ERROR)
- {
- ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
- ret = HandleCallback(ehRequest,
- rspGetFanCollection, rspFailureFan, payload, sizeof(payload));
- }
+ OCRepPayloadSetUri(payload, gRoomResourceUri);
+
+ OCRepPayload *tempPayload = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload, gLightResourceUri);
+ OCRepPayloadAppend(payload, tempPayload);
+
+ OCRepPayload *tempPayload2 = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload2, gFanResourceUri);
+ OCRepPayloadAppend(payload, tempPayload2);
}
else if(query.find(OC_RSRVD_INTERFACE_BATCH) != std::string::npos)
{
- 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));
- }
- if(ret != OC_EH_ERROR)
- {
- ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
- ret = HandleCallback(ehRequest,
- rspGetFanDefault, rspFailureFan, payload, sizeof(payload));
- }
+
+ OCRepPayloadSetUri(payload, gRoomResourceUri);
+
+ OCRepPayload *tempPayload = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload, gLightResourceUri);
+ OCRepPayloadSetPropBool(tempPayload, "state", false);
+ OCRepPayloadSetPropInt(tempPayload, "color", 0);
+ OCRepPayloadAppend(payload, tempPayload);
+
+ OCRepPayload *tempPayload2 = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload2, gFanResourceUri);
+ OCRepPayloadSetPropBool(tempPayload, "state", true);
+ OCRepPayloadSetPropInt(tempPayload, "speed", 10);
+ OCRepPayloadAppend(payload, tempPayload2);
}
if (ret == OC_EH_OK)
{
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ret;
- response.payload = payload;
- response.payloadSize = strlen(payload);
+ response.payload = reinterpret_cast<OCPayload*>(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
0, sizeof response.sendVendorSpecificHeaderOptions);
{
if(ret != OC_EH_ERROR)
{
- ret = HandleCallback(ehRequest,
- rspPutRoomDefault, rspFailureRoom, payload, sizeof(payload));
+ OCRepPayloadSetUri(payload, gRoomResourceUri);
+ OCRepPayloadSetPropString(payload, "name", "John's Room");
}
}
if(query.find(OC_RSRVD_INTERFACE_LL) != std::string::npos)
{
if(ret != OC_EH_ERROR)
{
- ret = HandleCallback(ehRequest,
- rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload));
+ OCRepPayloadSetUri(payload, gRoomResourceUri);
}
if(ret != OC_EH_ERROR)
{
- ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
- ret = HandleCallback(ehRequest,
- rspPutLightCollection, rspFailureLight, payload, sizeof(payload));
+ OCRepPayload *tempPayload = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload, gLightResourceUri);
+ OCRepPayloadAppend(payload, tempPayload);
}
if(ret != OC_EH_ERROR)
{
- ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
- ret = HandleCallback(ehRequest,
- rspPutFanCollection, rspFailureFan, payload, sizeof(payload));
+ OCRepPayload *tempPayload = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload, gFanResourceUri);
+ OCRepPayloadAppend(payload, tempPayload);
}
}
if(query.find(OC_RSRVD_INTERFACE_BATCH ) != std::string::npos)
{
if(ret != OC_EH_ERROR)
{
- ret = HandleCallback(ehRequest,
- rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload));
+ OCRepPayloadSetUri(payload, gRoomResourceUri);
}
if(ret != OC_EH_ERROR)
{
- ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
- ret = HandleCallback(ehRequest,
- rspPutLightDefault, rspFailureLight, payload, sizeof(payload));
+ OCRepPayload *tempPayload = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload, gLightResourceUri);
+ OCRepPayloadSetPropBool(tempPayload, "state", true);
+ OCRepPayloadSetPropInt(tempPayload, "color", 0);
+ OCRepPayloadAppend(payload, tempPayload);
}
if(ret != OC_EH_ERROR)
{
- ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
- ret = HandleCallback(ehRequest,
- rspPutFanDefault, rspFailureFan, payload, sizeof(payload));
+ OCRepPayload *tempPayload = OCRepPayloadCreate();
+ OCRepPayloadSetUri(tempPayload, gFanResourceUri);
+ OCRepPayloadSetPropBool(tempPayload, "state", false);
+ OCRepPayloadSetPropInt(tempPayload, "speed", 0);
+ OCRepPayloadAppend(payload, tempPayload);
}
}
if (ret == OC_EH_OK)
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ret;
- response.payload = payload;
- response.payloadSize = strlen(payload);
+ response.payload = reinterpret_cast<OCPayload*>(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
0, sizeof response.sendVendorSpecificHeaderOptions);
{
OCEntityHandlerResult ret = OC_EH_OK;
OCEntityHandlerResponse response;
- char payload[MAX_RESPONSE_LENGTH] = {0};
+ OCRepPayload* payload = OCRepPayloadCreate();
OC_LOG_V(INFO, TAG, "Callback for Light");
PrintReceivedMsgInfo(flag, ehRequest );
{
if(OC_REST_GET == ehRequest->method)
{
- ret = HandleCallback(ehRequest,
- rspGetLightDefault, rspFailureLight, payload, sizeof(payload));
+ OCRepPayloadSetUri(payload, gLightResourceUri);
+ OCRepPayloadSetPropBool(payload, "state", false);
+ OCRepPayloadSetPropInt(payload, "color", 0);
}
else if(OC_REST_PUT == ehRequest->method)
{
- ret = HandleCallback(ehRequest,
- rspPutLightDefault, rspFailureLight, payload, sizeof(payload));
+ OCRepPayloadSetUri(payload, gLightResourceUri);
+ OCRepPayloadSetPropBool(payload, "state", true);
+ OCRepPayloadSetPropInt(payload, "color", 0);
}
else
{
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ret;
- response.payload = payload;
- response.payloadSize = strlen(payload);
+ response.payload = reinterpret_cast<OCPayload*>(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
0, sizeof response.sendVendorSpecificHeaderOptions);
{
OCEntityHandlerResult ret = OC_EH_OK;
OCEntityHandlerResponse response;
- char payload[MAX_RESPONSE_LENGTH] = {0};
+ OCRepPayload* payload = OCRepPayloadCreate();
OC_LOG_V(INFO, TAG, "Callback for Fan");
PrintReceivedMsgInfo(flag, ehRequest );
{
if(OC_REST_GET == ehRequest->method)
{
- ret = HandleCallback(ehRequest, rspGetFanDefault,
- rspFailureFan, payload, sizeof(payload));
+ OCRepPayloadSetUri(payload, gFanResourceUri);
+ OCRepPayloadSetPropBool(payload, "state", true);
+ OCRepPayloadSetPropInt(payload, "speed", 10);
}
else if(OC_REST_PUT == ehRequest->method)
{
- ret = HandleCallback(ehRequest, rspPutFanDefault,
- rspFailureFan, payload, sizeof(payload));
+ OCRepPayloadSetUri(payload, gFanResourceUri);
+ OCRepPayloadSetPropBool(payload, "state", false);
+ OCRepPayloadSetPropInt(payload, "speed", 0);
}
else
{
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ret;
- response.payload = payload;
- response.payloadSize = strlen(payload);
+ response.payload = reinterpret_cast<OCPayload*>(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
0, sizeof response.sendVendorSpecificHeaderOptions);
return 0;
}
+
void createResources()
{
light.state = false;
#include "logger.h"
#include "cJSON.h"
#include "ocserverslow.h"
+#include "ocpayload.h"
volatile sig_atomic_t gQuitFlag = 0;
//This function takes the request as an input and returns the response
//in JSON format.
-char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
+OCRepPayload* constructResponse (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;
- OC_LOG(INFO, TAG, "Entering constructJsonResponse");
+ OC_LOG(INFO, TAG, "Entering constructResponse");
if (ehRequest->resource == gLedInstance[0].handle)
{
if(OC_REST_PUT == ehRequest->method)
{
- cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
-
- if(!putJson)
+ if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
{
- OC_LOG(ERROR, TAG, "CreateObject result in null for putJson");
- cJSON_Delete(json);
- return NULL;
+ OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+ return nullptr;
}
- currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
- "on") ? true:false);
- currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
- cJSON_Delete(putJson);
+ OCRepPayload *putPayload = reinterpret_cast<OCRepPayload*> (ehRequest->payload);
+
+ int64_t power;
+ bool state;
+
+ if (OCRepPayloadGetPropBool(putPayload, "state", &state))
+ {
+ currLEDResource->state = state;
+ }
+ if (OCRepPayloadGetPropInt (putPayload, "power", &power))
+ {
+ currLEDResource->power = power;
+ }
}
- cJSON_AddStringToObject(json,"href",gResourceUri);
- format = cJSON_CreateObject();
+ OCRepPayload *response = OCRepPayloadCreate();
- if(!format)
+ if (!response)
{
- OC_LOG(ERROR, TAG, "CreateObject result in null for format");
- cJSON_Delete(json);
- return NULL;
+ OC_LOG_V(ERROR, TAG, "Memory allocation for response payload failed.");
}
- cJSON_AddItemToObject(json, "rep", format);
- cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
- cJSON_AddNumberToObject(format, "power", currLEDResource->power);
+ OCRepPayloadSetUri (response, gResourceUri);
+ OCRepPayloadSetPropBool(response, "state", currLEDResource->state);
+ OCRepPayloadSetPropInt(response, "power", currLEDResource->power);
- OC_LOG(INFO, TAG, "Before constructJsonResponse print");
- jsonResponse = cJSON_Print(json);
- OC_LOG(INFO, TAG, "Before constructJsonResponse delete");
- cJSON_Delete(json);
-
- OC_LOG(INFO, TAG, "Before constructJsonResponse return");
- return jsonResponse;
+ return response;
}
-void ProcessGetRequest (OCEntityHandlerRequest *ehRequest)
+void ProcessGetPutRequest (OCEntityHandlerRequest *ehRequest)
{
- OC_LOG(INFO, TAG, "Entering ProcessGetRequest");
- char *getResp = constructJsonResponse(ehRequest);
+ OC_LOG(INFO, TAG, "Entering ProcessGetPutRequest");
+
+ OCRepPayload *getResp = constructResponse(ehRequest);
if(!getResp)
{
- OC_LOG(ERROR, TAG, "Failed to constructJsonResponse");
+ OC_LOG(ERROR, TAG, "Failed to construct response");
return;
}
- OC_LOG(INFO, TAG, "After constructJsonResponse");
+
OCEntityHandlerResponse response;
// Format the response. Note this requires some info about the request
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = OC_EH_OK;
- response.payload = getResp;
- response.payloadSize = strlen(getResp) + 1;
+ response.payload = reinterpret_cast<OCPayload*> (getResp);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
0, sizeof response.sendVendorSpecificHeaderOptions);
OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
{
OC_LOG(INFO, TAG, "Copying received request for slow response");
- OCEntityHandlerRequest *request =
+
+ OCEntityHandlerRequest *copyOfRequest =
(OCEntityHandlerRequest *)OICMalloc(sizeof(OCEntityHandlerRequest));
- if (request)
+
+ if (copyOfRequest)
{
// Do shallow copy
- memcpy(request, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
- // Do deep copy of query
- request->query =
- (char * )OICMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
- if (request->query)
- {
- strcpy((char *)request->query, (const char *)entityHandlerRequest->query);
+ memcpy(copyOfRequest, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
- // Copy the request payload
- request->reqJSONPayload = (char * )OICMalloc(
- strlen((const char *)entityHandlerRequest->reqJSONPayload) + 1);
- if (request->reqJSONPayload)
- {
- strcpy((char *)request->reqJSONPayload,
- (const char *)entityHandlerRequest->reqJSONPayload);
- // Ignore vendor specific header options for example
- request->numRcvdVendorSpecificHeaderOptions = 0;
- request->rcvdVendorSpecificHeaderOptions = NULL;
- }
- else
- {
- OICFree(request->query);
- OICFree(request);
- request = NULL;
- }
+ if (copyOfRequest->query)
+ {
+ // Do deep copy of query
+ copyOfRequest->query = (char *) OICMalloc(
+ strlen((const char *)entityHandlerRequest->query) + 1);
+
+ strcpy((char *)copyOfRequest->query, (const char *)entityHandlerRequest->query);
}
- else
+
+ if (entityHandlerRequest->payload)
{
- OICFree(request);
- request = NULL;
+ copyOfRequest->payload = reinterpret_cast<OCPayload*>
+ (OCRepPayloadClone ((OCRepPayload*) entityHandlerRequest->payload));
}
+
+ // Ignore vendor specific header options for example
+ copyOfRequest->numRcvdVendorSpecificHeaderOptions = 0;
+ copyOfRequest->rcvdVendorSpecificHeaderOptions = NULL;
}
- if (request)
+ if (copyOfRequest)
{
OC_LOG(INFO, TAG, "Copied client request");
}
{
OC_LOG(ERROR, TAG, "Error copying client request");
}
- return request;
+ return copyOfRequest;
}
-OCEntityHandlerResult
-OCEntityHandlerCb (OCEntityHandlerFlag flag,
+OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
OCEntityHandlerRequest *entityHandlerRequest, void* callbackParam)
{
OCEntityHandlerResult result = OC_EH_ERROR;
OCEntityHandlerRequest *request = NULL;
OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+
if (flag & OC_REQUEST_FLAG)
{
OC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
{
OC_LOG_V (INFO, TAG, "request query %s from client",
entityHandlerRequest->query);
- OC_LOG_V (INFO, TAG, "request payload %s from client",
- entityHandlerRequest->reqJSONPayload);
+ OC_LOG_PAYLOAD (INFO, TAG, entityHandlerRequest->payload);
+
// Make deep copy of received request and queue it for slow processing
request = CopyRequest(entityHandlerRequest);
+
if (request)
{
if (entityHandlerRequest->method == OC_REST_GET)
{
OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
- ProcessGetRequest (entityHandlerRequest);
+ ProcessGetPutRequest (entityHandlerRequest);
+ }
+ else if (entityHandlerRequest->method == OC_REST_PUT)
+ {
+ OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+ ProcessGetPutRequest (entityHandlerRequest);
}
else
{
}
// Free the request
OICFree(entityHandlerRequest->query);
- OICFree(entityHandlerRequest->reqJSONPayload);
+ OCPayloadDestroy(entityHandlerRequest->payload);
OICFree(entityHandlerRequest);
// If there are more requests in list, re-arm the alarm signal
return 0;
}
- /*
- * Declare and create the example resource: LED
- */
- createLEDResource(gResourceUri, &LED, false, 0);
+ // Declare and create the example resource: LED
+ createLEDResource(gResourceUri, &LED, false, 42);
// Initialize slow response alarm
signal(SIGALRM, AlarmHandler);
OC_LOG(ERROR, TAG, "OCStack process error");
return 0;
}
-
sleep(2);
}
for (auto iter = gRequestList.begin(); iter != gRequestList.end(); ++iter)
{
OICFree((*iter)->query);
- OICFree((*iter)->reqJSONPayload);
+ OCPayloadDestroy((*iter)->payload);
OICFree(*iter);
}
gRequestList.clear();
######################################################################
# Source files and Targets
######################################################################
+
ocserverbasicops = samples_env.Program('ocserverbasicops', ['common.cpp', 'ocserverbasicops.cpp'])
occlientbasicops = samples_env.Program('occlientbasicops', ['common.cpp', 'occlientbasicops.cpp'])
sec_samples_src_dir = src_dir + '/resource/csdk/stack/samples/linux/secure/'
sec_samples_build_dir = env.get('BUILD_DIR') +'/resource/csdk/stack/samples/linux/secure'
-samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
sec_samples_src_dir + 'oic_svr_db_server.json'))
-samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
sec_samples_src_dir + 'oic_svr_db_client.json'))
#include "ocstack.h"
#include "logger.h"
#include "occlientbasicops.h"
-#include "cJSON.h"
+#include "ocpayload.h"
#include "common.h"
#define TAG "occlientbasicops"
static int UNICAST_DISCOVERY = 0;
static int TEST_CASE = 0;
+static int CONN_TYPE = 0;
-static int IPV4_ADDR_SIZE = 16;
-static char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oic/res";
+static int IPV4_ADDR_SIZE = 24;
+static char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
+OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
-static std::string putPayload = "{\"oic\":[{\"rep\":{\"state\":\"off\",\"power\":10}}]}";
static std::string coapServerIP;
static std::string coapServerPort;
static std::string coapServerResource;
}
}
+OCPayload* putPayload()
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+
+ if(!payload)
+ {
+ std::cout << "Failed to create put payload object"<<std::endl;
+ std::exit(1);
+ }
+
+ OCRepPayloadSetPropInt(payload, "power", 15);
+ OCRepPayloadSetPropBool(payload, "state", true);
+
+ return (OCPayload*) payload;
+}
+
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, "-c 0 : Default auto-selection");
+ OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
}
OCStackResult InvokeOCDoResource(std::ostringstream &query,
cbData.cd = NULL;
ret = OCDoResource(NULL, method, query.str().c_str(), 0,
- (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
+ (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
ocConnType, qos, &cbData, options, numOptions);
if (ret != OC_STACK_OK)
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_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Put Response"));
}
return OC_STACK_DELETE_TRANSACTION;
}
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_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Post Response"));
}
return OC_STACK_DELETE_TRANSACTION;
}
{
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);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+ OC_LOG(INFO, TAG, PCF("=============> Get Response"));
}
return OC_STACK_DELETE_TRANSACTION;
}
{
OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
OC_LOG_V(INFO, TAG,
- "Device =============> Discovered %s @ %s:%d",
- clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ "Device =============> Discovered @ %s:%d",
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
+ OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
ocConnType = clientResponse->connType;
OCMethod method;
OCCallbackData cbData;
char szQueryUri[MAX_URI_LENGTH] = { 0 };
- OCConnectivityType discoveryReqConnType;
if (UNICAST_DISCOVERY)
{
char ipv4addr[IPV4_ADDR_SIZE];
- printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
+ OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
+ "(Ex: 11.12.13.14:1234)\n");
if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
{
//Strip newline char from ipv4addr
OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
return OC_STACK_INVALID_PARAM;
}
- discoveryReqConnType = CT_ADAPTER_IP;
method = OC_REST_GET;
}
else
int opt;
struct timespec timeout;
- while ((opt = getopt(argc, argv, "u:t:")) != -1)
+ while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
{
switch(opt)
{
case 't':
TEST_CASE = atoi(optarg);
break;
+ case 'c':
+ CONN_TYPE = atoi(optarg);
+ break;
default:
PrintUsage();
return -1;
}
if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
- (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
+ (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
+ (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
{
PrintUsage();
return -1;
}
+
+ if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE == CT_IP)
+ {
+ discoveryReqConnType = CT_DEFAULT;
+ }
+ else
+ {
+ OC_LOG(INFO, TAG, "Using Default Connectivity type");
+ PrintUsage();
+ }
+
+
// Initialize Persistent Storage for SVR database
OCPersistentStorage ps = {};
ps.open = client_fopen;
int parseClientResponse(OCClientResponse * clientResponse)
{
- int port = -1;
- cJSON * root = NULL;
- cJSON * oc = NULL;
+ OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
// Initialize all global variables
coapServerResource.clear();
coapServerIP.clear();
coapSecureResource = 0;
- root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
- if (!root)
- {
- return -1;
- }
-
- oc = cJSON_GetObjectItem(root,"oic");
- if (!oc)
+ while(res)
{
- return -1;
- }
+ coapServerResource.assign(res->uri);
+ OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
- if (oc->type == cJSON_Array)
- {
- int numRsrcs = cJSON_GetArraySize(oc);
- for(int i = 0; i < numRsrcs; i++)
+ if(res->secure)
{
- cJSON * resource = cJSON_GetArrayItem(oc, i);
- if (cJSON_GetObjectItem(resource, "href"))
- {
- coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
- }
- else
- {
- coapServerResource = "";
- }
- OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
+ coapSecureResource = 1;
+ }
- cJSON * prop = cJSON_GetObjectItem(resource,"prop");
- if (prop)
- {
- cJSON * policy = cJSON_GetObjectItem(prop,"p");
- if (policy)
- {
- // If this is a secure resource, the info about the port at which the
- // resource is hosted on server is embedded inside discovery JSON response
- if (cJSON_GetObjectItem(policy, "sec"))
- {
- if ((cJSON_GetObjectItem(policy, "sec")->valueint) == 1)
- {
- coapSecureResource = 1;
- }
- }
- OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
- if (cJSON_GetObjectItem(policy, "port"))
- {
- port = cJSON_GetObjectItem(policy, "port")->valueint;
- OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
-
- std::ostringstream ss;
- ss << port;
- coapServerPort = ss.str();
- }
- }
- }
+ OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
- // If we discovered a secure resource, exit from here
- if (coapSecureResource)
- {
- break;
- }
+ std::ostringstream ss;
+ ss << res->port;
+ coapServerPort = ss.str();
+ std::cout<<"PORT: "<<coapServerPort;
+
+ // If we discovered a secure resource, exit from here
+ if (coapSecureResource)
+ {
+ break;
}
+
+ res = res->next;
}
- cJSON_Delete(root);
coapServerIP = clientResponse->devAddr.addr;
- if (port == -1)
+
+ if(coapServerPort.length() == 0 || coapServerPort == "0")
{
coapServerPort = getPortTBServer(clientResponse);
OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
}
+
return 0;
}
MAX_TESTS
} CLIENT_TEST;
+/**
+ * List of connectivity types that can be initiated from the client
+ * Required for user input validation
+ */
+typedef enum {
+ CT_ADAPTER_DEFAULT = 0,
+ CT_IP,
+ MAX_CT
+} CLIENT_CONNECTIVITY_TYPE;
+
//-----------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------
#include <pthread.h>
#include "ocstack.h"
#include "logger.h"
-#include "cJSON.h"
+#include "ocpayload.h"
#include "ocserverbasicops.h"
#include "common.h"
//of other devices which the server trusts
static char CRED_FILE[] = "oic_svr_db_server.json";
+OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if(!payload)
+ {
+ OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+ return nullptr;
+ }
+
+ OCRepPayloadSetUri(payload, uri);
+ OCRepPayloadSetPropBool(payload, "state", state);
+ OCRepPayloadSetPropInt(payload, "power", power);
+
+ return payload;
+}
+
//This function takes the request as an input and returns the response
-//in JSON format.
-char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
{
- cJSON *json = cJSON_CreateObject();
- cJSON *putJson = NULL;
- cJSON *format;
- char *jsonResponse = NULL;
+ if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+ OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+ return nullptr;
+ }
+
+ OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
+
LEDResource *currLEDResource = &LED;
if (ehRequest->resource == gLedInstance[0].handle)
{
currLEDResource = &gLedInstance[0];
- gResourceUri = (char *) "a/led/0";
+ gResourceUri = (char *) "/a/led/0";
}
else if (ehRequest->resource == gLedInstance[1].handle)
{
currLEDResource = &gLedInstance[1];
- gResourceUri = (char *) "a/led/1";
+ gResourceUri = (char *) "/a/led/1";
}
if(OC_REST_PUT == ehRequest->method)
{
- cJSON* jsonObj = NULL;
- putJson = cJSON_Parse(ehRequest->reqJSONPayload);
- if(putJson)
+ // Get pointer to query
+ int64_t pow;
+ if(OCRepPayloadGetPropInt(input, "power", &pow))
{
- jsonObj = cJSON_GetObjectItem(putJson,"oic");
- if (jsonObj)
- {
- jsonObj = cJSON_GetArrayItem(jsonObj, 0);
- if (jsonObj)
- {
- jsonObj = cJSON_GetObjectItem(jsonObj, "rep");
- }
- }
+ currLEDResource->power =pow;
}
- if (NULL == jsonObj)
+
+ bool state;
+ if(OCRepPayloadGetPropBool(input, "state", &state))
{
- OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
- goto exit;
+ currLEDResource->state = state;
}
-
- currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(jsonObj,"state")->valuestring ,
- "on") ? true:false);
- currLEDResource->power = cJSON_GetObjectItem(jsonObj,"power")->valuedouble;
}
- cJSON_AddStringToObject(json,"href",gResourceUri);
- cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
- cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
- cJSON_AddNumberToObject(format, "power", currLEDResource->power);
-
- jsonResponse = cJSON_Print(json);
-
-exit:
- cJSON_Delete(putJson);
- cJSON_Delete(json);
- return jsonResponse;
+ return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
}
OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
- char *payload, size_t maxPayloadSize)
+ OCRepPayload **payload)
{
OCEntityHandlerResult ehResult;
- char *getResp = constructJsonResponse(ehRequest);
+ OCRepPayload *getResp = constructResponse(ehRequest);
+
if(getResp)
{
- 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);
+ *payload = getResp;
+ ehResult = OC_EH_OK;
}
else
{
}
OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
- char *payload, size_t maxPayloadSize)
+ OCRepPayload **payload)
{
OCEntityHandlerResult ehResult;
- char *putResp = constructJsonResponse(ehRequest);
+ OCRepPayload *putResp = constructResponse(ehRequest);
if(putResp)
{
- 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);
+ *payload = putResp;
+ ehResult = OC_EH_OK;
}
else
{
}
OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
- char *payload, size_t maxPayloadSize)
+ OCEntityHandlerResponse *response, OCRepPayload **payload)
{
- char *respPLPost_led = NULL;
- cJSON *json;
- cJSON *format;
- OCEntityHandlerResult ehResult;
+ OCRepPayload *respPLPost_led = nullptr;
+ OCEntityHandlerResult ehResult = OC_EH_OK;
/*
* The entity handler determines how to process a POST request.
int newLedUriLength = strlen(newLedUri);
snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
- json = cJSON_CreateObject();
-
- cJSON_AddStringToObject(json,"href",gResourceUri);
- cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
- cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
+ respPLPost_led = OCRepPayloadCreate();
+ OCRepPayloadSetUri(respPLPost_led, gResourceUri);
+ OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
{
gLedInstance[gCurrLedInstance].state = 0;
gLedInstance[gCurrLedInstance].power = 0;
gCurrLedInstance++;
- respPLPost_led = cJSON_Print(json);
+ strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
+ ehResult = OC_EH_RESOURCE_CREATED;
}
-
- cJSON_Delete(json);
}
else
{
- respPLPost_led = constructJsonResponse(ehRequest);
+ respPLPost_led = constructResponse(ehRequest);
}
}
else
{
if (i == 0)
{
- respPLPost_led = constructJsonResponse(ehRequest);
+ respPLPost_led = constructResponse(ehRequest);
break;
}
else if (i == 1)
{
- respPLPost_led = constructJsonResponse(ehRequest);
+ respPLPost_led = constructResponse(ehRequest);
}
}
}
}
- if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led)))
+ if (respPLPost_led != NULL)
{
- strcpy(payload, respPLPost_led);
+ *payload = respPLPost_led;
ehResult = OC_EH_OK;
}
else
{
- OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
+ OC_LOG_V (INFO, TAG, "Payload was NULL");
ehResult = OC_EH_ERROR;
}
- free(respPLPost_led);
-
return ehResult;
}
OCEntityHandlerResult ehResult = OC_EH_ERROR;
OCEntityHandlerResponse response;
- char payload[MAX_RESPONSE_LENGTH] = {0};
+
+ // Validate pointer
+ if (!entityHandlerRequest)
+ {
+ OC_LOG (ERROR, TAG, "Invalid request pointer");
+ return OC_EH_ERROR;
+ }
+
+ OCRepPayload* payload = nullptr;
if (flag & OC_REQUEST_FLAG)
{
if (OC_REST_GET == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
- ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload));
+ ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
}
else if (OC_REST_PUT == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
- ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload));
+ ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
}
else if (OC_REST_POST == entityHandlerRequest->method)
{
OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
- ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload));
+ ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
}
else
{
ehResult = OC_EH_ERROR;
}
- if (ehResult == OC_EH_OK)
+ if (ehResult == OC_EH_OK && 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 = payload;
- response.payloadSize = strlen(payload);
+ response.payload = reinterpret_cast<OCPayload*>(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
memset(response.resourceUri, 0, sizeof(response.resourceUri));
}
}
}
+
+ OCPayloadDestroy(response.payload);
return ehResult;
}
int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
/* This method converts the payload to JSON format */
-char* constructJsonResponse (OCEntityHandlerRequest *ehRequest);
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
/* Following methods process the PUT, GET, POST
* requests
*/
OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- size_t maxPayloadSize);
+ OCRepPayload **payload);
OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- size_t maxPayloadSize);
+ OCRepPayload **payload);
OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
- char *payload,
- size_t maxPayloadSize);
+ OCEntityHandlerResponse *response,
+ OCRepPayload **payload);
//-----------------------------------------------------------------------------
// Callback functions
OC_LOG(INFO, TAG, PCF("deleting tokens"));
OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)cbNode->token, cbNode->tokenLength);
CADestroyToken (cbNode->token);
+ OICFree(cbNode->devAddr);
OICFree(cbNode->handle);
OICFree(cbNode->requestUri);
if(cbNode->deleteCallback)
#include "cJSON.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "ocpayload.h"
/// Module Name
#include <stdio.h>
return OC_STACK_OK;
}
-
-static OCStackResult BuildRootResourceJSON(OCResource *resource,
- char * bufferPtr, uint16_t *remaining)
-{
- OCStackResult ret = OC_STACK_ERROR;
- cJSON *resObj = NULL;
- char *jsonStr = NULL;
- uint16_t jsonLen;
-
- OC_LOG(INFO, TAG, PCF("Entering BuildRootResourceJSON"));
- resObj = cJSON_CreateObject();
-
- 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)
- {
- OICStrcpy(bufferPtr, *remaining, jsonStr);
- *remaining -= jsonLen;
- bufferPtr += jsonLen;
- ret = OC_STACK_OK;
- }
- }
- else
- {
- ret = OC_STACK_INVALID_PARAM;
- }
-
- cJSON_Delete (resObj);
- OICFree(jsonStr);
-
- return ret;
-}
-
-
static OCStackResult
HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest, uint8_t filterOn, char *filterValue)
{
return OC_STACK_INVALID_PARAM;
}
- OCStackResult ret = OC_STACK_ERROR;
- char jsonbuffer[MAX_RESPONSE_LENGTH] = {};
- size_t jsonbufferLength = 0;
- uint16_t remaining = 0;
- char *ptr = NULL;
+ OCStackResult ret = OC_STACK_OK;
OCResource *collResource = (OCResource *)ehRequest->resource;
- ptr = jsonbuffer;
- remaining = MAX_RESPONSE_LENGTH;
-
- ret = BuildRootResourceJSON(collResource, ptr, &remaining);
-
- if (ret == OC_STACK_OK && remaining >= (sizeof (OC_JSON_SEPARATOR) + 1))
+ OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ if(!payload)
{
- ptr += strlen((char*)ptr);
- *ptr = OC_JSON_SEPARATOR;
- ptr++;
- remaining--;
+ ret = OC_STACK_NO_MEMORY;
}
- else
+
+ if(ret == OC_STACK_OK)
{
- ret = OC_STACK_ERROR;
+ ret = BuildVirtualResourceResponse(collResource, payload,
+ CA_ADAPTER_IP);
}
if (ret == OC_STACK_OK)
{
- for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+ for (int i = 0; i < MAX_CONTAINED_RESOURCES && ret == OC_STACK_OK; i++)
{
OCResource* temp = collResource->rsrcResources[i];
if (temp)
{
- //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_ADAPTER_IP);
- 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--;
- }
- // No point continuing as no more space on buffer
- // and/or no more resources.
- else
- {
- break;
- }
- }
- else
- {
- break;
+ //TODO : Add resource type filtering once collections
+ // start supporting queries.
+ ret = BuildVirtualResourceResponse(temp, payload,
+ CA_ADAPTER_IP);
}
}
}
- jsonbufferLength = strlen((const char *)jsonbuffer);
- if(ret == OC_STACK_OK && jsonbufferLength)
+ if(ret == OC_STACK_OK)
{
OCEntityHandlerResponse response = {};
response.ehResult = OC_EH_OK;
- response.payload = jsonbuffer;
- response.payloadSize = jsonbufferLength + 1;
+ response.payload = (OCPayload*)payload;
response.persistentBufferFlag = 0;
response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
response.resourceHandle = (OCResourceHandle) collResource;
ret = OCDoResponse(&response);
}
+ OCDiscoveryPayloadDestroy(payload);
return ret;
}
{
OCStackResult stackRet = OC_STACK_ERROR;
OCEntityHandlerResult ehResult = OC_EH_ERROR;
- char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
- size_t jsonbufferLength = 0;
- uint16_t remaining = 0;
- char * ptr = NULL;
OCResource * collResource = (OCResource *) ehRequest->resource;
- ptr = jsonbuffer;
- remaining = MAX_RESPONSE_LENGTH;
+ OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ if(!payload)
+ {
+ stackRet = OC_STACK_NO_MEMORY;
+ }
- stackRet = BuildRootResourceJSON(collResource, ptr, &remaining);
- ptr += strlen((char*)ptr);
+ if(stackRet == OC_STACK_OK)
+ {
+ stackRet = BuildVirtualResourceResponse(collResource, payload,
+ CA_ADAPTER_IP);
+ }
- jsonbufferLength = strlen((const char *)jsonbuffer);
- if(jsonbufferLength)
+ if(stackRet == OC_STACK_OK)
{
OCEntityHandlerResponse response = {};
response.ehResult = OC_EH_OK;
- response.payload = jsonbuffer;
- response.payloadSize = jsonbufferLength + 1;
+ response.payload = (OCPayload*)payload;
response.persistentBufferFlag = 0;
response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
response.resourceHandle = (OCResourceHandle) collResource;
stackRet = OCDoResponse(&response);
}
+ OCDiscoveryPayloadDestroy(payload);
if (stackRet == OC_STACK_OK)
{
OC_LOG(INFO, TAG, PCF("STACK_IF_BATCH"));
((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler =
HandleAggregateResponse;
+
((OCServerRequest *)ehRequest->requestHandle)->numResponses =
GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
+
return HandleBatchInterface(ehRequest);
+
case STACK_IF_GROUP:
return BuildCollectionGroupActionJSONResponse(OC_REST_GET/*flag*/,
(OCResource *) ehRequest->resource, ehRequest);
case STACK_IF_GROUP:
{
- OC_LOG_V(INFO, TAG, "IF_COLLECTION PUT with request ::\n%s\n ",
- ehRequest->reqJSONPayload);
+ OC_LOG(INFO, TAG, PCF("IF_COLLECTION PUT with request ::\n"));
+ OC_LOG_PAYLOAD(INFO, TAG, ehRequest->payload);
return BuildCollectionGroupActionJSONResponse(OC_REST_PUT/*flag*/,
(OCResource *) ehRequest->resource, ehRequest);
}
{
case STACK_IF_GROUP:
{
- OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
- ehRequest->reqJSONPayload);
+ OC_LOG(INFO, TAG, PCF("IF_COLLECTION POST with request ::\n"));
+ OC_LOG_PAYLOAD(INFO, TAG, ehRequest->payload);
return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
(OCResource *) ehRequest->resource, ehRequest);
}
if(ifQueryParam == STACK_IF_GROUP)
{
- OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
- ehRequest->reqJSONPayload);
+ OC_LOG(INFO, TAG, PCF("IF_COLLECTION POST with request ::\n"));
+ OC_LOG_PAYLOAD(INFO, TAG, ehRequest->payload);
return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
(OCResource *) ehRequest->resource, ehRequest);
}
#include "ocrandom.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "ocpayload.h"
#include "ocserverrequest.h"
-#include "cJSON.h"
#include "utlist.h"
#include "pdu.h"
#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
static struct ResourceObserver * serverObsList = NULL;
-#ifdef WITH_PRESENCE
-static char* GetJSONStringForPresence(uint32_t ttl, uint32_t nonce,
- OCPresenceTrigger trigger, OCResourceType *resourceType)
-{
- char *jsonEncodedInfo = NULL;
- const char * triggerStr = NULL;
-
- cJSON *rootObj = cJSON_CreateObject();
- VERIFY_NON_NULL (rootObj);
-
- cJSON_AddItemToObject (rootObj, OC_RSRVD_TTL, cJSON_CreateNumber(ttl));
-
- cJSON_AddItemToObject (rootObj, OC_RSRVD_NONCE, cJSON_CreateNumber(nonce));
-
- triggerStr = convertTriggerEnumToString(trigger);
- cJSON_AddItemToObject (rootObj, OC_RSRVD_TRIGGER, cJSON_CreateString(triggerStr));
-
- if(resourceType && resourceType->resourcetypename)
- {
- cJSON_AddItemToObject (rootObj, OC_RSRVD_RESOURCE_TYPE,
- cJSON_CreateString(resourceType->resourcetypename));
- }
-
- jsonEncodedInfo = cJSON_PrintUnformatted (rootObj);
-
-exit:
- cJSON_Delete(rootObj);
-
- return jsonEncodedInfo;
-
-}
-
-static OCStackResult BuildPresenceResponse(char *out, uint16_t *remaining,
- uint32_t ttl, uint32_t nonce, OCPresenceTrigger trigger,
- OCResourceType *resourceType)
-{
- if(!out || !remaining)
- {
- return OC_STACK_INVALID_PARAM;
- }
-
- OCStackResult ret = OC_STACK_ERROR;
- char *jsonStr = NULL;
- uint16_t jsonLen = 0;
-
- jsonStr = GetJSONStringForPresence(ttl, nonce, trigger, resourceType);
-
- if(jsonStr)
- {
- jsonLen = strlen(jsonStr);
-
- if (jsonLen < *remaining)
- {
- OICStrcpy(out, *remaining, jsonStr);
- *remaining = *remaining - jsonLen;
- ret = OC_STACK_OK;
- }
- else
- {
- ret = OC_STACK_ERROR;
- }
-
- OICFree(jsonStr);
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("Error encoding presence payload."));
- ret = OC_STACK_ERROR;
- }
- return ret;
-}
-#endif // WITH_PRESENCE
/**
* Determine observe QOS based on the QOS of the request.
* The qos passed as a parameter overrides what the client requested.
{
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
request->method, (OCResourceHandle) resPtr, request->query,
- request->reqJSONPayload,
+ request->payload, request->payloadSize,
request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
OC_OBSERVE_NO_OPTION, 0);
else
{
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"));
if(result == OC_STACK_OK)
{
- uint16_t remaining = MAX_RESPONSE_LENGTH;
- // create the payload here
- result = BuildPresenceResponse(presenceResBuf, &remaining,
- maxAge, resPtr->sequenceNum, trigger,
- resourceType);
+ OCPresencePayload* presenceResBuf = OCPresencePayloadCreate(
+ resPtr->sequenceNum, maxAge, trigger,
+ resourceType ? resourceType->resourcetypename : NULL);
- if(result == OC_STACK_OK && remaining < MAX_RESPONSE_LENGTH)
+ if(!presenceResBuf)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ if(result == OC_STACK_OK)
{
ehResponse.ehResult = OC_EH_OK;
- ehResponse.payload = presenceResBuf;
- ehResponse.payloadSize = strlen((const char *)presenceResBuf) + 1;
+ ehResponse.payload = (OCPayload*)presenceResBuf;
ehResponse.persistentBufferFlag = 0;
ehResponse.requestHandle = (OCRequestHandle) request;
ehResponse.resourceHandle = (OCResourceHandle) resPtr;
resourceObserver->resUri);
result = OCDoResponse(&ehResponse);
}
+
+ OCPresencePayloadDestroy(presenceResBuf);
}
}
#endif
OCStackResult SendListObserverNotification (OCResource * resource,
OCObservationId *obsIdList, uint8_t numberOfIds,
- const char *notificationJSONPayload, uint32_t maxAge,
+ const OCRepPayload *payload,
+ uint32_t maxAge,
OCQualityOfService qos)
{
- if(!resource || !obsIdList || !notificationJSONPayload)
+ if(!resource || !obsIdList || !payload)
{
return OC_STACK_INVALID_PARAM;
}
{
OCEntityHandlerResponse ehResponse = {};
ehResponse.ehResult = OC_EH_OK;
- ehResponse.payload = (char *) OICMalloc(MAX_RESPONSE_LENGTH + 1);
+ ehResponse.payload = (OCPayload*)OCRepPayloadCreate();
if(!ehResponse.payload)
{
FindAndDeleteServerRequest(request);
continue;
}
- OICStrcpy(ehResponse.payload, MAX_RESPONSE_LENGTH + 1,
- notificationJSONPayload);
- ehResponse.payloadSize = strlen(ehResponse.payload) + 1;
+ memcpy(ehResponse.payload, payload, sizeof(*payload));
ehResponse.persistentBufferFlag = 0;
ehResponse.requestHandle = (OCRequestHandle) request;
ehResponse.resourceHandle = (OCResourceHandle) resource;
--- /dev/null
+//******************************************************************
+//
+// 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 "ocpayload.h"
+#include "octypes.h"
+#include <string.h>
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "ocstackinternal.h"
+#include "ocresource.h"
+#include "logger.h"
+
+#define TAG "OCPayload"
+static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val);
+
+void OCPayloadDestroy(OCPayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+
+ switch(payload->type)
+ {
+ case PAYLOAD_TYPE_REPRESENTATION:
+ OCRepPayloadDestroy((OCRepPayload*)payload);
+ break;
+ case PAYLOAD_TYPE_DISCOVERY:
+ OCDiscoveryPayloadDestroy((OCDiscoveryPayload*)payload);
+ break;
+ case PAYLOAD_TYPE_DEVICE:
+ OCDevicePayloadDestroy((OCDevicePayload*)payload);
+ break;
+ case PAYLOAD_TYPE_PLATFORM:
+ OCPlatformPayloadDestroy((OCPlatformPayload*)payload);
+ break;
+ case PAYLOAD_TYPE_PRESENCE:
+ OCPresencePayloadDestroy((OCPresencePayload*)payload);
+ break;
+ case PAYLOAD_TYPE_SECURITY:
+ OCSecurityPayloadDestroy((OCSecurityPayload*)payload);
+ break;
+ default:
+ OC_LOG_V(ERROR, TAG, "Unsupported payload type in destroy: %d", payload->type);
+ OICFree(payload);
+ break;
+ }
+}
+OCRepPayload* OCRepPayloadCreate()
+{
+ OCRepPayload* payload = (OCRepPayload*)OICCalloc(1, sizeof(OCRepPayload));
+
+ if(!payload)
+ {
+ return NULL;
+ }
+
+ payload->base.type = PAYLOAD_TYPE_REPRESENTATION;
+
+ return payload;
+}
+
+void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child)
+{
+ if(!parent)
+ {
+ return;
+ }
+
+ while(parent->next)
+ {
+ parent = parent->next;
+ }
+
+ parent->next= child;
+}
+
+static OCRepPayloadValue* OCRepPayloadFindValue(const OCRepPayload* payload, const char* name)
+{
+ if(!payload || !name)
+ {
+ return NULL;
+ }
+
+ OCRepPayloadValue* val = payload->values;
+ while(val)
+ {
+ if(0 == strcmp(val->name, name))
+ {
+ return val;
+ }
+ val = val->next;
+ }
+
+ return NULL;
+
+}
+
+static void OCCopyPropertyValueArray(OCRepPayloadValue* dest, OCRepPayloadValue* source)
+{
+ size_t dimTotal = calcDimTotal(source->arr.dimensions);
+ switch(source->arr.type)
+ {
+ case OCREP_PROP_INT:
+ dest->arr.iArray = (int64_t*)OICMalloc(dimTotal * sizeof(int64_t));
+ memcpy(dest->arr.iArray, source->arr.iArray, dimTotal * sizeof(int64_t));
+ break;
+ case OCREP_PROP_DOUBLE:
+ dest->arr.dArray = (double*)OICMalloc(dimTotal * sizeof(double));
+ memcpy(dest->arr.dArray, source->arr.dArray, dimTotal * sizeof(double));
+ break;
+ case OCREP_PROP_BOOL:
+ dest->arr.bArray = (bool*)OICMalloc(dimTotal * sizeof(bool));
+ memcpy(dest->arr.bArray, source->arr.bArray, dimTotal * sizeof(bool));
+ break;
+ case OCREP_PROP_STRING:
+ dest->arr.strArray = (char**)OICMalloc(dimTotal * sizeof(char*));
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ dest->arr.strArray[i] = OICStrdup(source->arr.strArray[i]);
+ }
+ break;
+ case OCREP_PROP_ARRAY:
+ dest->arr.objArray = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*));
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ dest->arr.objArray[i] = OCRepPayloadClone(source->arr.objArray[i]);
+ }
+ break;
+ default:
+ OC_LOG(ERROR, TAG, PCF("CopyPropertyValueArray invalid type"));
+ break;
+ }
+}
+
+static void OCCopyPropertyValue (OCRepPayloadValue *dest, OCRepPayloadValue *source)
+{
+ if (!source || !dest)
+ {
+ return;
+ }
+
+ switch(source->type)
+ {
+ case OCREP_PROP_STRING:
+ dest->str = OICStrdup(source->str);
+ break;
+ case OCREP_PROP_OBJECT:
+ dest->obj = OCRepPayloadClone(source->obj);
+ break;
+ case OCREP_PROP_ARRAY:
+ OCCopyPropertyValueArray(dest, source);
+ break;
+ default:
+ // Nothing to do for the trivially copyable types.
+ break;
+ }
+}
+
+static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
+{
+ if(!val)
+ {
+ return;
+ }
+
+ if(val->type == OCREP_PROP_STRING)
+ {
+ OICFree(val->str);
+ }
+ else if (val->type == OCREP_PROP_OBJECT)
+ {
+ OCRepPayloadDestroy(val->obj);
+ }
+ else if (val->type == OCREP_PROP_ARRAY)
+ {
+ size_t dimTotal = calcDimTotal(val->arr.dimensions);
+ switch(val->arr.type)
+ {
+ case OCREP_PROP_INT:
+ case OCREP_PROP_DOUBLE:
+ case OCREP_PROP_BOOL:
+ // Since this is a union, iArray will
+ // point to all of the above
+ OICFree(val->arr.iArray);
+ break;
+ case OCREP_PROP_STRING:
+ for(size_t i = 0; i< dimTotal;++i)
+ {
+ OICFree(val->arr.strArray[i]);
+ }
+ OICFree(val->arr.strArray);
+ break;
+ case OCREP_PROP_OBJECT:
+ for(size_t i = 0; i< dimTotal;++i)
+ {
+ OCRepPayloadDestroy(val->arr.objArray[i]);
+ }
+ OICFree(val->arr.objArray);
+ break;
+ case OCREP_PROP_NULL:
+ case OCREP_PROP_ARRAY:
+ OC_LOG_V(ERROR, TAG, "FreeRepPayloadValueContents: Illegal type\
+ inside an array: %d", val->arr.type);
+ break;
+ }
+ }
+}
+
+static void OCFreeRepPayloadValue(OCRepPayloadValue* val)
+{
+ if(!val)
+ {
+ return;
+ }
+
+ OICFree(val->name);
+ OCFreeRepPayloadValueContents(val);
+ OCFreeRepPayloadValue(val->next);
+ OICFree(val);
+}
+static OCRepPayloadValue* OCRepPayloadValueClone (OCRepPayloadValue* source)
+{
+ if (!source)
+ {
+ return NULL;
+ }
+
+ OCRepPayloadValue *sourceIter = source;
+ OCRepPayloadValue *destIter = (OCRepPayloadValue*) OICCalloc(1, sizeof(OCRepPayloadValue));
+ if (!destIter)
+ {
+ return NULL;
+ }
+
+ OCRepPayloadValue *headOfClone = destIter;
+
+ // Copy payload type and non pointer types in union.
+ *destIter = *sourceIter;
+ destIter->name = OICStrdup (sourceIter->name);
+ OCCopyPropertyValue (destIter, sourceIter);
+
+ sourceIter = sourceIter->next;
+
+ while (sourceIter)
+ {
+ destIter->next = (OCRepPayloadValue*) OICCalloc(1, sizeof(OCRepPayloadValue));
+ if (!destIter->next)
+ {
+ OCFreeRepPayloadValue (headOfClone);
+ return NULL;
+ }
+
+ *(destIter->next) = *sourceIter;
+ destIter->next->name = OICStrdup (sourceIter->name);
+ OCCopyPropertyValue (destIter->next, sourceIter);
+
+ sourceIter = sourceIter->next;
+ destIter = destIter->next;
+ }
+ return headOfClone;
+}
+
+static OCRepPayloadValue* OCRepPayloadFindAndSetValue(OCRepPayload* payload, const char* name,
+ OCRepPayloadPropType type)
+{
+ if(!payload || !name)
+ {
+ return NULL;
+ }
+
+ OCRepPayloadValue* val = payload->values;
+ if(val == NULL)
+ {
+ payload->values = (OCRepPayloadValue*)OICCalloc(1, sizeof(OCRepPayloadValue));
+ payload->values->name = OICStrdup(name);
+ payload->values->type =type;
+ return payload->values;
+ }
+
+ while(val)
+ {
+ if(0 == strcmp(val->name, name))
+ {
+ OCFreeRepPayloadValueContents(val);
+ val->type = type;
+ return val;
+ }
+ else if(val->next == NULL)
+ {
+ val->next = (OCRepPayloadValue*)OICCalloc(1, sizeof(OCRepPayloadValue));
+ val->next->name = OICStrdup(name);
+ val->next->type =type;
+ return val->next;
+ }
+
+ val = val->next;
+ }
+
+ OC_LOG(ERROR, TAG, PCF("FindAndSetValue reached point after while loop, pointer corruption?"));
+ return NULL;
+}
+
+bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType)
+{
+ return OCRepPayloadAddResourceTypeAsOwner(payload, OICStrdup(resourceType));
+}
+
+bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType)
+{
+ if(!payload || !resourceType)
+ {
+ return false;
+ }
+
+ if(payload->types)
+ {
+ OCStringLL* cur = payload->types;
+ while(cur->next)
+ {
+ cur = cur->next;
+ }
+ cur->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+
+ if(!cur->next)
+ {
+ return false;
+ }
+
+ cur->next->value = resourceType;
+ return true;
+ }
+ else
+ {
+ payload->types = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ if(!payload->types)
+ {
+ return false;
+ }
+ payload->types->value = resourceType;
+ return true;
+ }
+}
+
+bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface)
+{
+ return OCRepPayloadAddInterfaceAsOwner(payload, OICStrdup(interface));
+}
+
+bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
+{
+ if(!payload || !interface)
+ {
+ return false;
+ }
+
+ if(payload->interfaces)
+ {
+ OCStringLL* cur = payload->interfaces;
+ while(cur->next)
+ {
+ cur = cur->next;
+ }
+ cur->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+
+ if(!cur->next)
+ {
+ return false;
+ }
+ cur->next->value = interface;
+ return true;
+ }
+ else
+ {
+ payload->interfaces = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ if(!payload->interfaces)
+ {
+ return false;
+ }
+ payload->interfaces->value = interface;
+ return true;
+ }
+}
+
+bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri)
+{
+ if(!payload)
+ {
+ return false;
+ }
+
+ payload->uri = OICStrdup(uri);
+ return payload->uri != NULL;
+}
+
+bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ return val->type == OCREP_PROP_NULL;
+}
+
+bool OCRepPayloadSetNull(OCRepPayload* payload, const char* name)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_NULL);
+ return val != NULL;
+}
+
+bool OCRepPayloadSetPropInt(OCRepPayload* payload,
+ const char* name, int64_t value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_INT);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->i = value;
+ return true;
+}
+
+bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64_t* value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_INT)
+ {
+ return false;
+ }
+
+ *value = val->i;
+ return true;
+}
+
+bool OCRepPayloadSetPropDouble(OCRepPayload* payload,
+ const char* name, double value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_DOUBLE);
+
+ if(!val )
+ {
+ return false;
+ }
+
+ val->d = value;
+ return true;
+}
+
+bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_DOUBLE)
+ {
+ return false;
+ }
+
+ *value = val->d;
+ return true;
+}
+
+bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value)
+{
+ char* temp = OICStrdup(value);
+ bool b = OCRepPayloadSetPropStringAsOwner(payload, name, temp);
+
+ if(!b)
+ {
+ OICFree(temp);
+ }
+ return b;
+}
+
+bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_STRING);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->str = value;
+ return val->str != NULL;
+}
+
+bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, const char** value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_STRING)
+ {
+ return false;
+ }
+
+ *value = OICStrdup(val->str);
+ return *value != NULL;
+}
+
+bool OCRepPayloadSetPropBool(OCRepPayload* payload,
+ const char* name, bool value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_BOOL);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->b = value;
+ return true;
+}
+
+bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool* value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_BOOL)
+ {
+ return false;
+ }
+
+ *value = val->b;
+ return true;
+}
+
+bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value)
+{
+ OCRepPayload* temp = OCRepPayloadClone(value);
+ bool b = OCRepPayloadSetPropObjectAsOwner(payload, name, temp);
+
+ if(!b)
+ {
+ OCRepPayloadDestroy(temp);
+ }
+ return b;
+}
+
+bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name, OCRepPayload* value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_OBJECT);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->obj = value;
+ return true;
+}
+
+bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_OBJECT)
+ {
+ return false;
+ }
+
+ *value = OCRepPayloadClone(val->obj);
+ return *value != NULL;
+}
+
+size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ if(dimensions[0] == 0)
+ {
+ return 0;
+ }
+
+ size_t total = 1;
+ for(uint8_t i = 0; i < MAX_REP_ARRAY_DEPTH && dimensions[i] != 0; ++i)
+ {
+ total *= dimensions[i];
+ }
+ return total;
+}
+
+bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
+ int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->arr.type = OCREP_PROP_INT;
+ memcpy(val->arr.dimensions, dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ val->arr.iArray = array;
+
+ return true;
+}
+
+bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
+ const int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ size_t dimTotal = calcDimTotal(dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+
+ int64_t* newArray = (int64_t*)OICMalloc(dimTotal * sizeof(int64_t));
+
+ if(!newArray)
+ {
+ return false;
+ }
+
+ memcpy(newArray, array, dimTotal * sizeof(int64_t));
+
+
+ bool b = OCRepPayloadSetIntArrayAsOwner(payload, name, newArray, dimensions);
+ if(!b)
+ {
+ OICFree(newArray);
+ }
+ return b;
+}
+
+bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
+ int64_t** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_INT
+ || !val->arr.iArray)
+ {
+ return false;
+ }
+
+ size_t dimTotal = calcDimTotal(val->arr.dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+ *array = (int64_t*)OICMalloc(dimTotal * sizeof(int64_t));
+ if(!*array)
+ {
+ return false;
+ }
+
+ memcpy(*array, val->arr.iArray, dimTotal * sizeof(int64_t));
+ memcpy(dimensions, val->arr.dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ return true;
+}
+
+bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
+ double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->arr.type = OCREP_PROP_DOUBLE;
+ memcpy(val->arr.dimensions, dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ val->arr.dArray = array;
+
+ return true;
+}
+bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
+ const double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ size_t dimTotal = calcDimTotal(dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+
+ double* newArray = (double*)OICMalloc(dimTotal * sizeof(double));
+
+ if(!newArray)
+ {
+ return false;
+ }
+
+ memcpy(newArray, array, dimTotal * sizeof(double));
+
+ bool b = OCRepPayloadSetDoubleArrayAsOwner(payload, name, newArray, dimensions);
+ if(!b)
+ {
+ OICFree(newArray);
+ }
+ return b;
+}
+
+bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
+ double** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_DOUBLE
+ || !val->arr.dArray)
+ {
+ return false;
+ }
+
+ size_t dimTotal = calcDimTotal(val->arr.dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+ *array = (double*)OICMalloc(dimTotal * sizeof(double));
+ if(!*array)
+ {
+ return false;
+ }
+
+ memcpy(*array, val->arr.dArray, dimTotal * sizeof(double));
+ memcpy(dimensions, val->arr.dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ return true;
+}
+
+bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
+ char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->arr.type = OCREP_PROP_STRING;
+ memcpy(val->arr.dimensions, dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ val->arr.strArray = array;
+
+ return true;
+}
+bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
+ const char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ size_t dimTotal = calcDimTotal(dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+
+ char** newArray = (char**)OICMalloc(dimTotal * sizeof(char*));
+
+ if(!newArray)
+ {
+ return false;
+ }
+
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ newArray[i] = OICStrdup(array[i]);
+ }
+
+ bool b = OCRepPayloadSetStringArrayAsOwner(payload, name, newArray, dimensions);
+
+ if(!b)
+ {
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ OICFree(newArray[i]);
+ }
+ OICFree(newArray);
+ }
+ return b;
+}
+
+bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
+ char*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_STRING
+ || !val->arr.strArray)
+ {
+ return false;
+ }
+
+ size_t dimTotal = calcDimTotal(val->arr.dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+ *array = (char**)OICMalloc(dimTotal * sizeof(char*));
+ if(!*array)
+ {
+ return false;
+ }
+
+ memcpy(dimensions, val->arr.dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ (*array)[i] = OICStrdup(val->arr.strArray[i]);
+ }
+
+ return true;
+
+}
+
+bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
+ bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->arr.type = OCREP_PROP_BOOL;
+ memcpy(val->arr.dimensions, dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ val->arr.bArray = array;
+
+ return true;
+}
+bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
+ const bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ size_t dimTotal = calcDimTotal(dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+
+ bool* newArray = (bool*)OICMalloc(dimTotal * sizeof(bool));
+
+ if(!newArray)
+ {
+ return false;
+ }
+
+ memcpy(newArray, array, dimTotal * sizeof(bool));
+
+
+ bool b = OCRepPayloadSetBoolArrayAsOwner(payload, name, newArray, dimensions);
+ if(!b)
+ {
+ OICFree(newArray);
+ }
+ return b;
+}
+
+bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
+ bool** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_BOOL
+ || !val->arr.bArray)
+ {
+ return false;
+ }
+
+ size_t dimTotal = calcDimTotal(val->arr.dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+ *array = (bool*)OICMalloc(dimTotal * sizeof(bool));
+ if(!*array)
+ {
+ return false;
+ }
+
+ memcpy(*array, val->arr.bArray, dimTotal * sizeof(bool));
+ memcpy(dimensions, val->arr.dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ return true;
+}
+
+bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* name,
+ OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
+
+ if(!val)
+ {
+ return false;
+ }
+
+ val->arr.type = OCREP_PROP_OBJECT;
+ memcpy(val->arr.dimensions, dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ val->arr.objArray = array;
+
+ return true;
+}
+
+bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
+ const OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ size_t dimTotal = calcDimTotal(dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+
+ OCRepPayload** newArray = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*));
+
+ if(!newArray)
+ {
+ return false;
+ }
+
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ newArray[i] = OCRepPayloadClone(array[i]);
+ }
+
+ bool b = OCRepPayloadSetPropObjectArrayAsOwner(payload, name, newArray, dimensions);
+
+ if(!b)
+ {
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ OCRepPayloadDestroy(newArray[i]);
+ }
+ OICFree(newArray);
+ }
+ return b;
+}
+
+bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* name,
+ OCRepPayload*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if(!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_OBJECT
+ || !val->arr.objArray)
+ {
+ return false;
+ }
+
+ size_t dimTotal = calcDimTotal(val->arr.dimensions);
+ if(dimTotal == 0)
+ {
+ return false;
+ }
+ *array = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*));
+ if(!*array)
+ {
+ return false;
+ }
+
+ memcpy(dimensions, val->arr.dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ (*array)[i] = OCRepPayloadClone(val->arr.objArray[i]);
+ }
+
+ return true;
+}
+
+void OCFreeOCStringLL(OCStringLL* ll)
+{
+ if(!ll)
+ {
+ return;
+ }
+
+ OCFreeOCStringLL(ll->next);
+ OICFree(ll->value);
+ OICFree(ll);
+}
+
+OCStringLL* CloneOCStringLL (OCStringLL* ll)
+{
+ if (!ll)
+ {
+ return NULL;
+ }
+
+ OCStringLL *sourceIter = ll;
+
+ OCStringLL *destIter = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
+ if (!destIter)
+ {
+ return NULL;
+ }
+ destIter->value = OICStrdup (sourceIter->value);
+
+ OCStringLL *headOfClone = destIter;
+
+ sourceIter = sourceIter->next;
+
+ while (sourceIter)
+ {
+ destIter->next = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL));
+ if (!destIter->next)
+ {
+ OCFreeOCStringLL (headOfClone);
+ return NULL;
+ }
+ destIter->next->value = OICStrdup (sourceIter->value);
+
+ destIter = destIter->next;
+ sourceIter = sourceIter->next;
+ }
+ return headOfClone;
+}
+
+OCRepPayload* OCRepPayloadClone (const OCRepPayload* payload)
+{
+ if (!payload)
+ {
+ return NULL;
+ }
+
+ OCRepPayload *clone = OCRepPayloadCreate();
+
+ if (!clone)
+ {
+ return NULL;
+ }
+
+ clone->uri = OICStrdup (payload->uri);
+ clone->types = CloneOCStringLL (payload->types);
+ clone->interfaces = CloneOCStringLL (payload->interfaces);
+ clone->values = OCRepPayloadValueClone (payload->values);
+
+ return clone;
+}
+
+
+void OCRepPayloadDestroy(OCRepPayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+
+ OICFree(payload->uri);
+ OCFreeOCStringLL(payload->types);
+ OCFreeOCStringLL(payload->interfaces);
+ OCFreeRepPayloadValue(payload->values);
+ OCRepPayloadDestroy(payload->next);
+ OICFree(payload);
+}
+
+OCDiscoveryPayload* OCDiscoveryPayloadCreate()
+{
+ OCDiscoveryPayload* payload = (OCDiscoveryPayload*)OICCalloc(1, sizeof(OCDiscoveryPayload));
+
+ if(!payload)
+ {
+ return NULL;
+ }
+
+ payload->base.type = PAYLOAD_TYPE_DISCOVERY;
+
+ return payload;
+}
+
+OCSecurityPayload* OCSecurityPayloadCreate(char* securityData)
+{
+ OCSecurityPayload* payload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+
+ if(!payload)
+ {
+ return NULL;
+ }
+
+ payload->base.type = PAYLOAD_TYPE_SECURITY;
+ payload->securityData = OICStrdup(securityData);
+
+ return payload;
+}
+
+void OCSecurityPayloadDestroy(OCSecurityPayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+
+ OICFree(payload->securityData);
+ OICFree(payload);
+}
+
+size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload)
+{
+ size_t i = 0;
+ OCResourcePayload* p = payload->resources;
+ while(p)
+ {
+ ++i;
+ p = p->next;
+ }
+ return i;
+}
+
+OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index)
+{
+ size_t i = 0;
+ OCResourcePayload* p = payload->resources;
+ while(p)
+ {
+ if(i == index)
+ {
+ return p;
+ }
+ ++i;
+ p = p->next;
+ }
+ return NULL;
+}
+
+static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t port)
+{
+ OCResourcePayload* pl = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
+ if(!pl)
+ {
+ return NULL;
+ }
+
+ pl->uri = OICStrdup(res->uri);
+ pl->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
+ memcpy(pl->sid, OCGetServerInstanceID(), UUID_SIZE);
+
+ // types
+ OCResourceType* typePtr = res->rsrcType;
+
+ if(typePtr != NULL)
+ {
+ pl->types = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ pl->types->value = OICStrdup(typePtr->resourcetypename);
+
+ OCStringLL* cur = pl->types;
+ typePtr = typePtr->next;
+ while(typePtr)
+ {
+ cur->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ cur->next->value = OICStrdup(typePtr->resourcetypename);
+ cur = cur->next;
+ typePtr = typePtr->next;
+ }
+ }
+
+ // interfaces
+ OCResourceInterface* ifPtr = res->rsrcInterface;
+ if(ifPtr != NULL)
+ {
+ pl->interfaces = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ pl->interfaces->value = OICStrdup(ifPtr->name);
+
+ OCStringLL* cur = pl->interfaces;
+ ifPtr = ifPtr->next;
+ while(ifPtr)
+ {
+ cur->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ cur->next->value = OICStrdup(ifPtr->name);
+ cur = cur->next;
+ ifPtr = ifPtr->next;
+ }
+ }
+
+ pl->bitmap = res->resourceProperties & (OC_OBSERVABLE | OC_DISCOVERABLE);
+ pl->secure = (res->resourceProperties & OC_SECURE) != 0;
+ pl->port = port;
+
+ return pl;
+}
+
+void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+ uint16_t port)
+{
+ OCDiscoveryPayloadAddNewResource(payload, OCCopyResource(res, port));
+}
+
+void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res)
+{
+ if(!payload->resources)
+ {
+ payload->resources = res;
+ }
+ else
+ {
+ OCResourcePayload* p = payload->resources;
+ while(p->next)
+ {
+ p = p->next;
+ }
+ p->next = res;
+ }
+}
+
+void FreeOCDiscoveryResource(OCResourcePayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+
+ OICFree(payload->uri);
+ OICFree(payload->sid);
+ OCFreeOCStringLL(payload->types);
+ OCFreeOCStringLL(payload->interfaces);
+ FreeOCDiscoveryResource(payload->next);
+ OICFree(payload);
+
+}
+void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+
+ FreeOCDiscoveryResource(payload->resources);
+ OICFree(payload);
+}
+
+OCDevicePayload* OCDevicePayloadCreate(const char* uri, const uint8_t* sid, const char* dname,
+ const char* specVer, const char* dmVer)
+{
+
+ OCDevicePayload* payload = (OCDevicePayload*)OICCalloc(1, sizeof(OCDevicePayload));
+
+ if(!payload)
+ {
+ return NULL;
+ }
+
+ payload->base.type = PAYLOAD_TYPE_DEVICE;
+
+ payload->uri = OICStrdup(uri);
+ if(uri && !payload->uri)
+ {
+ goto exit;
+ }
+
+ if(sid)
+ {
+ payload->sid = (uint8_t*)OICMalloc(UUID_SIZE);
+ if(!payload->sid)
+ {
+ goto exit;
+ }
+ memcpy(payload->sid, sid, UUID_SIZE);
+ }
+
+ payload->deviceName = OICStrdup(dname);
+ if(dname && !payload->deviceName)
+ {
+ goto exit;
+ }
+
+ payload->specVersion = OICStrdup(specVer);
+ if(specVer && !payload->specVersion)
+ {
+ goto exit;
+ }
+
+ payload->dataModelVersion = OICStrdup(dmVer);
+ if(dmVer && !payload->dataModelVersion)
+ {
+ goto exit;
+ }
+
+ return payload;
+
+exit:
+ OCDevicePayloadDestroy((OCDevicePayload*)payload);
+ return NULL;
+}
+
+void OCDevicePayloadDestroy(OCDevicePayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+
+ OICFree(payload->uri);
+ OICFree(payload->sid);
+ OICFree(payload->deviceName);
+ OICFree(payload->specVersion);
+ OICFree(payload->dataModelVersion);
+ OICFree(payload);
+}
+
+static void OCCopyPlatformInfo(const OCPlatformInfo* platformInfo, OCPlatformPayload* target)
+{
+ target->info.platformID = OICStrdup(platformInfo->platformID);
+ target->info.manufacturerName = OICStrdup(platformInfo->manufacturerName);
+ target->info.manufacturerUrl = OICStrdup(platformInfo->manufacturerUrl);
+ target->info.modelNumber = OICStrdup(platformInfo->modelNumber);
+ target->info.dateOfManufacture = OICStrdup(platformInfo->dateOfManufacture);
+ target->info.platformVersion = OICStrdup(platformInfo->platformVersion);
+ target->info.operatingSystemVersion = OICStrdup(platformInfo->operatingSystemVersion);
+ target->info.hardwareVersion = OICStrdup(platformInfo->hardwareVersion);
+ target->info.firmwareVersion = OICStrdup(platformInfo->firmwareVersion);
+ target->info.supportUrl = OICStrdup(platformInfo->supportUrl);
+ target->info.systemTime = OICStrdup(platformInfo->systemTime);
+}
+
+OCPlatformPayload* OCPlatformPayloadCreateAsOwner(char* uri, OCPlatformInfo* platformInfo)
+{
+ OCPlatformPayload* payload = (OCPlatformPayload*)OICCalloc(1, sizeof(OCPlatformPayload));
+ if(!payload)
+ {
+ return NULL;
+ }
+
+ payload->base.type = PAYLOAD_TYPE_PLATFORM;
+ payload->uri = uri;
+ payload->info = *platformInfo;
+
+ return payload;
+}
+
+OCPlatformPayload* OCPlatformPayloadCreate(const char* uri, const OCPlatformInfo* platformInfo)
+{
+ OCPlatformPayload* payload = (OCPlatformPayload*)OICCalloc(1, sizeof(OCPlatformPayload));
+
+ if(!payload)
+ {
+ return NULL;
+ }
+
+ payload->base.type = PAYLOAD_TYPE_PLATFORM;
+ payload->uri = OICStrdup(uri);
+ OCCopyPlatformInfo(platformInfo, payload);
+
+ return payload;
+}
+
+void OCPlatformPayloadDestroy(OCPlatformPayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+ OICFree(payload->uri);
+ OICFree(payload->info.platformID);
+ OICFree(payload->info.manufacturerName);
+ OICFree(payload->info.manufacturerUrl);
+ OICFree(payload->info.modelNumber);
+ OICFree(payload->info.dateOfManufacture);
+ OICFree(payload->info.platformVersion);
+ OICFree(payload->info.operatingSystemVersion);
+ OICFree(payload->info.hardwareVersion);
+ OICFree(payload->info.firmwareVersion);
+ OICFree(payload->info.supportUrl);
+ OICFree(payload->info.systemTime);
+ OICFree(payload);
+}
+
+OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
+ OCPresenceTrigger trigger, const char* resourceType)
+{
+ OCPresencePayload* payload = (OCPresencePayload*)OICCalloc(1, sizeof(OCPresencePayload));
+ if(!payload)
+ {
+ return NULL;
+ }
+
+ payload->base.type = PAYLOAD_TYPE_PRESENCE;
+ payload->sequenceNumber = seqNum;
+ payload->maxAge = maxAge;
+ payload->trigger = trigger;
+ payload->resourceType = OICStrdup(resourceType);
+ return payload;
+}
+
+void OCPresencePayloadDestroy(OCPresencePayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+ OICFree(payload->resourceType);
+ OICFree(payload);
+}
--- /dev/null
+//******************************************************************
+//
+// 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 "ocpayloadcbor.h"
+#include <stdlib.h>
+#include "oic_malloc.h"
+#include "logger.h"
+#include "ocpayload.h"
+#include "ocrandom.h"
+#include "ocresourcehandler.h"
+#include "cbor.h"
+
+#define TAG PCF("OCPayloadConvert")
+
+static OCStackResult OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t** outPayload,
+ size_t* size);
+static OCStackResult OCConvertDevicePayload(OCDevicePayload* payload, uint8_t** outPayload,
+ size_t* size);
+static OCStackResult OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t** outPayload,
+ size_t* size);
+static OCStackResult OCConvertRepPayload(OCRepPayload* payload, uint8_t** outPayload, size_t* size);
+static OCStackResult OCConvertPresencePayload(OCPresencePayload* payload, uint8_t** outPayload,
+ size_t* size);
+static OCStackResult OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t** outPayload,
+ size_t* size);
+
+bool AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+ const char* value);
+
+bool ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+ const char* value);
+
+
+OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size)
+{
+ OC_LOG_V(INFO, TAG, "Converting payload of type %d", payload->type);
+ switch(payload->type)
+ {
+ case PAYLOAD_TYPE_DISCOVERY:
+ return OCConvertDiscoveryPayload((OCDiscoveryPayload*)payload, outPayload, size);
+ case PAYLOAD_TYPE_DEVICE:
+ return OCConvertDevicePayload((OCDevicePayload*)payload, outPayload, size);
+ case PAYLOAD_TYPE_PLATFORM:
+ return OCConvertPlatformPayload((OCPlatformPayload*)payload, outPayload, size);
+ case PAYLOAD_TYPE_REPRESENTATION:
+ return OCConvertRepPayload((OCRepPayload*)payload, outPayload, size);
+ case PAYLOAD_TYPE_PRESENCE:
+ return OCConvertPresencePayload((OCPresencePayload*)payload, outPayload, size);
+ case PAYLOAD_TYPE_SECURITY:
+ return OCConvertSecurityPayload((OCSecurityPayload*)payload, outPayload, size);
+ default:
+ OC_LOG_V(INFO,TAG, "ConvertPayload default %d", payload->type);
+ return OC_STACK_NOTIMPL;
+ }
+}
+
+static OCStackResult OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t** outPayload,
+ size_t* size)
+{
+ *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
+ *size = MAX_REQUEST_LENGTH;
+
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ CborEncoder encoder;
+ bool err = false;
+
+ cbor_encoder_init(&encoder, *outPayload, *size, 0);
+
+ CborEncoder rootArray;
+ err = err || cbor_encoder_create_array(&encoder, &rootArray, 2);
+ err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_SECURITY);
+
+ CborEncoder map;
+
+ err = err || cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+
+ if(payload->securityData)
+ {
+ err = err || AddTextStringToMap(&map, OC_RSRVD_REPRESENTATION,
+ sizeof(OC_RSRVD_REPRESENTATION) - 1,
+ payload->securityData);
+ }
+
+ err = err || cbor_encoder_close_container(&rootArray, &map);
+
+ err = err || cbor_encoder_close_container(&encoder, &rootArray);
+
+ if(err)
+ {
+ OC_LOG_V(ERROR, TAG, "Convert Security Payload failed", err);
+ OICFree(*outPayload);
+ return OC_STACK_ERROR;
+ }
+
+ *size = encoder.ptr - *outPayload;
+ uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
+
+ if(!tempPayload)
+ {
+ OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
+ OICFree(*outPayload);
+ return OC_STACK_ERROR;
+ }
+
+ *outPayload = tempPayload;
+ return OC_STACK_OK;
+}
+
+static OCStackResult OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t** outPayload,
+ size_t* size)
+{
+ *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
+ *size = MAX_REQUEST_LENGTH;
+
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ CborEncoder encoder = {};
+ bool err = false;
+ size_t resourceCount = OCDiscoveryPayloadGetResourceCount(payload);
+
+ cbor_encoder_init(&encoder, *outPayload, *size, 0);
+
+ CborEncoder rootArray;
+ err = err || cbor_encoder_create_array(&encoder, &rootArray, 1 + resourceCount);
+ err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_DISCOVERY);
+
+ for(size_t i = 0; i < resourceCount; ++i)
+ {
+ CborEncoder map;
+ OCResourcePayload* resource = OCDiscoveryPayloadGetResource(payload, i);
+ err = err || cbor_encoder_create_map(&rootArray, &map, 3);
+ // Uri
+ err = err || AddTextStringToMap(&map, OC_RSRVD_HREF,
+ sizeof(OC_RSRVD_HREF) - 1,
+ resource->uri);
+
+ // Server ID
+ err = err || cbor_encode_text_string(&map, OC_RSRVD_SERVER_INSTANCE_ID,
+ sizeof(OC_RSRVD_SERVER_INSTANCE_ID) - 1);
+ err = err || cbor_encode_byte_string(&map, resource->sid, UUID_SIZE);
+ // Prop Tag
+ {
+ CborEncoder propMap;
+ err = err || cbor_encode_text_string(&map, OC_RSRVD_PROPERTY,
+ sizeof(OC_RSRVD_PROPERTY) -1 );
+ err = err || cbor_encoder_create_map(&map, &propMap, 3);
+
+ // Resource Type
+ {
+ CborEncoder rtArray;
+ err = err || cbor_encode_text_string(&propMap, OC_RSRVD_RESOURCE_TYPE,
+ sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
+ err = err || cbor_encoder_create_array(&propMap, &rtArray, CborIndefiniteLength);
+
+ OCStringLL* rtPtr = resource->types;
+ while(rtPtr)
+ {
+ err = err || cbor_encode_text_string(&rtArray, rtPtr->value,
+ strlen(rtPtr->value));
+ rtPtr = rtPtr->next;
+ }
+
+ err = err || cbor_encoder_close_container(&propMap, &rtArray);
+ }
+
+ // Interface Types
+ {
+ CborEncoder ifArray;
+ err = err || cbor_encode_text_string(&propMap, OC_RSRVD_INTERFACE,
+ sizeof(OC_RSRVD_INTERFACE) - 1);
+ err = err || cbor_encoder_create_array(&propMap, &ifArray, CborIndefiniteLength);
+ OCStringLL* ifPtr = resource->interfaces;
+
+ while(ifPtr)
+ {
+ err = err || cbor_encode_text_string(&ifArray, ifPtr->value,
+ strlen(ifPtr->value));
+ ifPtr= ifPtr->next;
+ }
+
+ err = err || cbor_encoder_close_container(&propMap, &ifArray);
+ }
+ // Policy
+ {
+ CborEncoder policyMap;
+ err = err || cbor_encode_text_string(&propMap, OC_RSRVD_POLICY,
+ sizeof(OC_RSRVD_POLICY) - 1);
+ err = err || cbor_encoder_create_map(&propMap, &policyMap, CborIndefiniteLength);
+
+ // Bitmap
+ err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
+ sizeof(OC_RSRVD_BITMAP) - 1);
+ err = err || cbor_encode_uint(&policyMap, resource->bitmap);
+
+ if(resource->secure)
+ {
+ err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
+ sizeof(OC_RSRVD_SECURE) - 1);
+ err = err || cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
+
+ if(resource->port != 0)
+ {
+ err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
+ sizeof(OC_RSRVD_HOSTING_PORT) - 1);
+ err = err || cbor_encode_uint(&policyMap, resource->port);
+ }
+ }
+
+ err = err || cbor_encoder_close_container(&propMap, &policyMap);
+ }
+ // Close
+ err = err || cbor_encoder_close_container(&map, &propMap);
+ }
+ // Close Item
+ err = err || cbor_encoder_close_container(&rootArray, &map);
+ }
+ // Close main array
+ err = err || cbor_encoder_close_container(&encoder, &rootArray);
+
+ if(err)
+ {
+ OC_LOG_V(ERROR, TAG, "Convert Discovery Payload failed with : %d", err);
+ return OC_STACK_ERROR;
+ }
+
+ *size = encoder.ptr - *outPayload;
+ uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
+
+ if(!tempPayload)
+ {
+ OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
+ OICFree(*outPayload);
+ return OC_STACK_ERROR;
+ }
+
+ *outPayload = tempPayload;
+ return OC_STACK_OK;
+}
+
+static OCStackResult OCConvertDevicePayload(OCDevicePayload* payload, uint8_t** outPayload,
+ size_t* size)
+{
+ *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
+ *size = MAX_REQUEST_LENGTH;
+
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ CborEncoder encoder = {};
+ bool err = false;
+
+ cbor_encoder_init(&encoder, *outPayload, *size, 0);
+ CborEncoder rootArray;
+ err = err || cbor_encoder_create_array(&encoder, &rootArray, 2);
+ err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_DEVICE);
+
+ {
+ CborEncoder map;
+ err = err || cbor_encoder_create_map(&rootArray, &map, 2);
+
+ // uri
+ err = err || AddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
+ payload->uri);
+
+ // Rep Map
+ {
+ CborEncoder repMap;
+ err = err || cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
+ sizeof(OC_RSRVD_REPRESENTATION) - 1);
+ err = err || cbor_encoder_create_map(&map, &repMap, 4);
+
+ // Device ID
+ err = err || cbor_encode_text_string(&repMap, OC_RSRVD_DEVICE_ID,
+ sizeof(OC_RSRVD_DEVICE_ID) - 1);
+ err = err || cbor_encode_byte_string(&repMap, payload->sid, UUID_SIZE);
+
+ // Device Name
+ err = err || AddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
+ sizeof(OC_RSRVD_DEVICE_NAME) - 1,
+ payload->deviceName);
+
+ // Device Spec Version
+ err = err || AddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
+ sizeof(OC_RSRVD_SPEC_VERSION) - 1,
+ payload->specVersion);
+
+ // Device data Model Version
+ err = err || AddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
+ sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1,
+ payload->dataModelVersion);
+
+ err = err || cbor_encoder_close_container(&map, &repMap);
+ }
+
+ // Close Map
+ err = err || cbor_encoder_close_container(&rootArray, &map);
+ }
+
+ // Close main array
+ err = err || cbor_encoder_close_container(&encoder, &rootArray);
+
+ if(err)
+ {
+ OC_LOG_V(ERROR, TAG, "Convert Device Payload failed with : %d", err);
+ return OC_STACK_ERROR;
+ }
+
+ *size = encoder.ptr - *outPayload;
+ uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
+
+ if(!tempPayload)
+ {
+ OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
+ OICFree(*outPayload);
+ return OC_STACK_ERROR;
+ }
+
+ *outPayload = tempPayload;
+ return OC_STACK_OK;
+}
+
+static OCStackResult OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t** outPayload,
+ size_t* size)
+{
+ *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
+ *size = MAX_REQUEST_LENGTH;
+
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ CborEncoder encoder = {};
+ bool err = false;
+
+ cbor_encoder_init(&encoder, *outPayload, *size, 0);
+ CborEncoder rootArray;
+ err = err || cbor_encoder_create_array(&encoder, &rootArray, 2);
+ err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_PLATFORM);
+ {
+ CborEncoder map;
+ err = err || cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+
+ // uri
+ err = err || AddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
+ payload->uri);
+
+ // Rep Map
+ {
+ CborEncoder repMap;
+ err = err || cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
+ sizeof(OC_RSRVD_REPRESENTATION) - 1);
+ err = err || cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
+
+ // Platform ID
+ err = err || AddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
+ sizeof(OC_RSRVD_PLATFORM_ID) - 1,
+ payload->info.platformID);
+
+ // MFG Name
+ err = err || AddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
+ sizeof(OC_RSRVD_MFG_NAME) - 1,
+ payload->info.manufacturerName);
+
+ // MFG Url
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
+ sizeof(OC_RSRVD_MFG_URL) - 1,
+ payload->info.manufacturerUrl);
+
+ // Model Num
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
+ sizeof(OC_RSRVD_MODEL_NUM) - 1,
+ payload->info.modelNumber);
+
+ // Date of Mfg
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
+ sizeof(OC_RSRVD_MFG_DATE) - 1,
+ payload->info.dateOfManufacture);
+
+ // Platform Version
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
+ sizeof(OC_RSRVD_PLATFORM_VERSION) - 1,
+ payload->info.platformVersion);
+
+ // OS Version
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
+ sizeof(OC_RSRVD_OS_VERSION) - 1,
+ payload->info.operatingSystemVersion);
+
+ // Hardware Version
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
+ sizeof(OC_RSRVD_HARDWARE_VERSION) - 1,
+ payload->info.hardwareVersion);
+
+ // Firmware Version
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
+ sizeof(OC_RSRVD_FIRMWARE_VERSION) - 1,
+ payload->info.firmwareVersion);
+
+ // Support URL
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
+ sizeof(OC_RSRVD_SUPPORT_URL) - 1,
+ payload->info.supportUrl);
+
+ // System Time
+ err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
+ sizeof(OC_RSRVD_SYSTEM_TIME) - 1,
+ payload->info.systemTime);
+ err = err || cbor_encoder_close_container(&map, &repMap);
+ }
+
+ // Close Map
+ err = err || cbor_encoder_close_container(&rootArray, &map);
+ }
+
+ // Close main array
+ err = err || cbor_encoder_close_container(&encoder, &rootArray);
+
+ if(err)
+ {
+ OC_LOG_V(ERROR, TAG, "Convert Platform Payload failed with : %d", err);
+ return OC_STACK_ERROR;
+ }
+
+ *size = encoder.ptr - *outPayload;
+ uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
+
+ if(!tempPayload)
+ {
+ OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
+ OICFree(*outPayload);
+ return OC_STACK_ERROR;
+ }
+
+ *outPayload = tempPayload;
+
+ return OC_STACK_OK;
+}
+
+static bool OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload);
+
+static bool OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray* valArray)
+{
+ CborEncoder array;
+ bool err = false;
+
+ err = err || cbor_encoder_create_array(parent, &array, CborIndefiniteLength);
+ err = err || cbor_encode_uint(&array, valArray->type);
+ for(int i = 0; i < MAX_REP_ARRAY_DEPTH; ++i)
+ {
+ err = err || cbor_encode_uint(&array, valArray->dimensions[i]);
+ }
+
+ size_t dimTotal = calcDimTotal(valArray->dimensions);
+
+ for(size_t i = 0; i < dimTotal; ++i)
+ {
+ switch(valArray->type)
+ {
+ case OCREP_PROP_NULL:
+ OC_LOG(ERROR, TAG, PCF("ConvertArray Invalid NULL"));
+ err = CborUnknownError;
+ break;
+ case OCREP_PROP_INT:
+ err = err || cbor_encode_int(&array, valArray->iArray[i]);
+ break;
+ case OCREP_PROP_DOUBLE:
+ err = err || cbor_encode_double(&array, valArray->dArray[i]);
+ break;
+ case OCREP_PROP_BOOL:
+ err = err || cbor_encode_boolean(&array, valArray->bArray[i]);
+ break;
+ case OCREP_PROP_STRING:
+ err = err || cbor_encode_text_string(&array, valArray->strArray[i],
+ strlen(valArray->strArray[i]));
+ break;
+ case OCREP_PROP_OBJECT:
+ err = OCConvertSingleRepPayload(&array, valArray->objArray[i]);
+ break;
+ case OCREP_PROP_ARRAY:
+ OC_LOG(ERROR, TAG, PCF("ConvertArray Invalid child array"));
+ err = CborUnknownError;
+ break;
+ }
+ }
+
+ err = err || cbor_encoder_close_container(parent, &array);
+ return err;
+}
+
+static bool OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload)
+{
+ bool err = false;
+ CborEncoder map;
+ err = err || cbor_encoder_create_map(parent, &map, CborIndefiniteLength);
+
+ // Uri
+ err = err || ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF,
+ sizeof(OC_RSRVD_HREF) - 1,
+ payload->uri);
+
+ // Prop Map
+ // resource types, interfaces
+ if(payload->types || payload->interfaces)
+ {
+ OC_LOG_V(INFO, TAG, "Payload has types or interfaces");
+ err = err || cbor_encode_text_string(&map,
+ OC_RSRVD_PROPERTY,
+ sizeof(OC_RSRVD_PROPERTY) - 1);
+ CborEncoder propMap;
+ err = err || cbor_encoder_create_map(&map, &propMap, 2);
+
+ CborEncoder curArray;
+ if(payload->types)
+ {
+ err = err || cbor_encode_text_string(&propMap,
+ OC_RSRVD_RESOURCE_TYPE,
+ sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
+ err = err || cbor_encoder_create_array(&propMap, &curArray, CborIndefiniteLength);
+ OCStringLL* val = payload->types;
+ while(val)
+ {
+ err = err || cbor_encode_text_string(&curArray, val->value, strlen(val->value));
+ val = val->next;
+ }
+ err = err || cbor_encoder_close_container(&propMap, &curArray);
+ }
+ if(payload->interfaces)
+ {
+ err = err || cbor_encode_text_string(&propMap,
+ OC_RSRVD_INTERFACE,
+ sizeof(OC_RSRVD_INTERFACE) - 1);
+ err = err || cbor_encoder_create_array(&propMap, &curArray, CborIndefiniteLength);
+ OCStringLL* val = payload->interfaces;
+ while(val)
+ {
+ err = err || cbor_encode_text_string(&curArray, val->value, strlen(val->value));
+ val = val->next;
+ }
+ err = err || cbor_encoder_close_container(&propMap, &curArray);
+ }
+ err = err || cbor_encoder_close_container(&map, &propMap);
+ }
+
+ // Rep Map
+ {
+ CborEncoder repMap;
+ err = err || cbor_encode_text_string(&map,
+ OC_RSRVD_REPRESENTATION,
+ sizeof(OC_RSRVD_REPRESENTATION) - 1);
+ err = err || cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
+ OCRepPayloadValue* value = payload->values;
+ while(value)
+ {
+ err = err || cbor_encode_text_string(&repMap,
+ value->name,
+ strlen(value->name));
+ switch(value->type)
+ {
+ case OCREP_PROP_NULL:
+ err = err || cbor_encode_null(&repMap);
+ break;
+ case OCREP_PROP_INT:
+ err = err || cbor_encode_int(&repMap,
+ value->i);
+ break;
+ case OCREP_PROP_DOUBLE:
+ err = err || cbor_encode_double(&repMap,
+ value->d);
+ break;
+ case OCREP_PROP_BOOL:
+ err = err || cbor_encode_boolean(&repMap,
+ value->b);
+ break;
+ case OCREP_PROP_STRING:
+ err = err || cbor_encode_text_string(&repMap,
+ value->str, strlen(value->str));
+ break;
+ case OCREP_PROP_OBJECT:
+ err = err || OCConvertSingleRepPayload(&repMap, value->obj);
+ break;
+ case OCREP_PROP_ARRAY:
+ err = err || OCConvertArray(&repMap, &value->arr);
+ break;
+ default:
+ OC_LOG_V(ERROR, TAG, "Invalid Prop type: %d",
+ value->type);
+ break;
+ }
+ value = value->next;
+ }
+
+ err = err || cbor_encoder_close_container(&map, &repMap);
+ }
+
+ // Close Map
+ err = err || cbor_encoder_close_container(parent, &map);
+
+ return err;
+}
+
+static OCStackResult OCConvertRepPayload(OCRepPayload* payload, uint8_t** outPayload, size_t* size)
+{
+ *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
+ *size = MAX_REQUEST_LENGTH;
+
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ CborEncoder encoder = {};
+ bool err = false;
+
+ cbor_encoder_init(&encoder, *outPayload, *size, 0);
+ CborEncoder rootArray;
+ err = err || cbor_encoder_create_array(&encoder, &rootArray, CborIndefiniteLength);
+ err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_REPRESENTATION);
+
+ while(payload != NULL && !err)
+ {
+ err = err || OCConvertSingleRepPayload(&rootArray, payload);
+ payload = payload->next;
+ }
+
+ // Close main array
+ err = err || cbor_encoder_close_container(&encoder, &rootArray);
+
+ if(err)
+ {
+ OC_LOG_V(ERROR, TAG, "Convert Rep Payload failed with : %d", err);
+ return OC_STACK_ERROR;
+ }
+
+ *size = encoder.ptr - *outPayload;
+ uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
+
+ if(!tempPayload)
+ {
+ OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
+ OICFree(*outPayload);
+ return OC_STACK_ERROR;
+ }
+
+ *outPayload = tempPayload;
+
+ return OC_STACK_OK;
+}
+
+static OCStackResult OCConvertPresencePayload(OCPresencePayload* payload,
+ uint8_t** outPayload, size_t* size)
+{
+ *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
+ *size = MAX_REQUEST_LENGTH;
+
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ CborEncoder encoder = {};
+ bool err = false;
+
+ cbor_encoder_init(&encoder, *outPayload, *size, 0);
+ CborEncoder rootArray;
+
+ err = err || cbor_encoder_create_array(&encoder, &rootArray, 2);
+ err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_PRESENCE);
+
+
+ CborEncoder map;
+ err = err || cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+
+ // Sequence Number
+ err = err || cbor_encode_text_string(&map,
+ OC_RSRVD_NONCE,
+ sizeof(OC_RSRVD_NONCE) - 1);
+ err = err || cbor_encode_uint(&map, payload->sequenceNumber);
+
+ // Max Age
+ err = err || cbor_encode_text_string(&map,
+ OC_RSRVD_TTL,
+ sizeof(OC_RSRVD_TTL) - 1);
+ err = err || cbor_encode_uint(&map, payload->maxAge);
+
+ // Trigger
+ const char* triggerStr = convertTriggerEnumToString(payload->trigger);
+ err = err || AddTextStringToMap(&map, OC_RSRVD_TRIGGER, sizeof(OC_RSRVD_TRIGGER) - 1,
+ triggerStr);
+
+ // Resource type name
+ if(payload->trigger != OC_PRESENCE_TRIGGER_DELETE)
+ {
+ err = err || ConditionalAddTextStringToMap(&map, OC_RSRVD_RESOURCE_TYPE,
+ sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, payload->resourceType);
+ }
+
+ // Close Map
+ err = err || cbor_encoder_close_container(&rootArray, &map);
+ err = err || cbor_encoder_close_container(&encoder, &rootArray);
+
+ if(err)
+ {
+ OC_LOG_V(ERROR, TAG, "Convert Presence Payload failed with : %d", err);
+ return OC_STACK_ERROR;
+ }
+
+ *size = encoder.ptr - *outPayload;
+ uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
+
+ if(!tempPayload)
+ {
+ OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
+ OICFree(*outPayload);
+ return OC_STACK_ERROR;
+ }
+
+ *outPayload = tempPayload;
+
+ return OC_STACK_OK;
+}
+
+bool AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+ const char* value)
+{
+ return cbor_encode_text_string(map, key, keylen) ||
+ cbor_encode_text_string(map, value, strlen(value));
+}
+
+bool ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+ const char* value)
+{
+ return value ? AddTextStringToMap(map, key, keylen, value) : false;
+}
--- /dev/null
+//******************************************************************
+//
+// 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 "ocpayloadcbor.h"
+#include <stdlib.h>
+#include "logger.h"
+#include "oic_malloc.h"
+#include "ocstackinternal.h"
+#include "ocpayload.h"
+#include "cbor.h"
+
+#define TAG PCF("OCPayloadParse")
+
+static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue* arrayVal);
+static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arrayVal);
+static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* arrayVal);
+static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue* repParent);
+static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* arrayVal);
+static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* arrayVal);
+static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* arrayVal);
+
+OCStackResult OCParsePayload(OCPayload** outPayload, const uint8_t* payload, size_t payloadSize)
+{
+ CborParser parser;
+ CborValue rootValue;
+ bool err = false;
+
+ OC_LOG_V(INFO, TAG, "CBOR Parsing size: %d", payloadSize, payload);
+ if((err = cbor_parser_init(payload, payloadSize, 0, &parser, &rootValue)) != false)
+ {
+ OC_LOG_V(ERROR, TAG, "CBOR Parser init failed: %d", err);
+ return OC_STACK_ERROR;
+ }
+
+ if(!cbor_value_is_array(&rootValue))
+ {
+ OC_LOG_V(ERROR, TAG, "CBOR payload root object is not an array :%x", rootValue.type);
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+
+ CborValue arrayValue;
+ // enter the array
+ err = err || cbor_value_enter_container(&rootValue, &arrayValue);
+
+ int payloadType;
+ err = err || cbor_value_get_int(&arrayValue, &payloadType);
+ err = err || cbor_value_advance_fixed(&arrayValue);
+
+ if(err)
+ {
+ OC_LOG_V(ERROR, TAG, "CBOR payload parse failed :%d", err);
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+
+ OCStackResult result = OC_STACK_ERROR;
+ switch(payloadType)
+ {
+ case PAYLOAD_TYPE_DISCOVERY:
+ result = OCParseDiscoveryPayload(outPayload, &arrayValue);
+ break;
+ case PAYLOAD_TYPE_DEVICE:
+ result = OCParseDevicePayload(outPayload, &arrayValue);
+ break;
+ case PAYLOAD_TYPE_PLATFORM:
+ result = OCParsePlatformPayload(outPayload, &arrayValue);
+ break;
+ case PAYLOAD_TYPE_REPRESENTATION:
+ result = OCParseRepPayload(outPayload, &arrayValue);
+ break;
+ case PAYLOAD_TYPE_PRESENCE:
+ result = OCParsePresencePayload(outPayload, &arrayValue);
+ break;
+ case PAYLOAD_TYPE_SECURITY:
+ result = OCParseSecurityPayload(outPayload, &arrayValue);
+ break;
+ default:
+ OC_LOG_V(ERROR, TAG, "ParsePayload Type default: %d", payloadType);
+ result = OC_STACK_ERROR;
+ break;
+ }
+
+ if(result == OC_STACK_OK)
+ {
+ err = err || cbor_value_leave_container(&rootValue, &arrayValue);
+ if(err != CborNoError)
+ {
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+ }
+ else
+ {
+ OC_LOG_V(INFO, TAG, "Finished parse payload, result is %d", result);
+ }
+
+ return result;
+}
+
+void OCFreeOCStringLL(OCStringLL* ll);
+
+static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* arrayVal)
+{
+ bool err = false;
+ char * securityData = NULL;
+
+ if(cbor_value_is_map(arrayVal))
+ {
+ CborValue curVal;
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
+
+ if(cbor_value_is_valid(&curVal))
+ {
+ size_t len;
+ err = err || cbor_value_dup_text_string(&curVal, &securityData, &len, NULL);
+ }
+ }
+ else
+ {
+ OC_LOG_V(ERROR, TAG, PCF("Cbor main value not a map"));
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+
+ err = err || cbor_value_advance(arrayVal);
+
+ if(err)
+ {
+ OC_LOG_V(ERROR, TAG, "Cbor in error condition");
+ OICFree(securityData);
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+
+ *outPayload = (OCPayload*)OCSecurityPayloadCreate(securityData);
+ OICFree(securityData);
+
+ return OC_STACK_OK;
+
+}
+
+static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue* arrayVal)
+{
+ bool err = false;
+
+ OCDiscoveryPayload* out = OCDiscoveryPayloadCreate();
+
+ if(!out)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ size_t resourceCount = 0;
+ while(!err &&
+ cbor_value_is_map(arrayVal))
+ {
+ OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
+ if(!resource)
+ {
+ OC_LOG_V(ERROR, TAG, "Memory allocation failed");
+ return OC_STACK_NO_MEMORY;
+ }
+ CborValue curVal;
+
+ // Uri
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
+ size_t len;
+ err = err || cbor_value_dup_text_string(&curVal, &(resource->uri), &len, NULL);
+
+ // SID
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_SERVER_INSTANCE_ID, &curVal);
+ err = err || cbor_value_dup_byte_string(&curVal, &(resource->sid), &len, NULL);
+
+ // Prop Tag
+ {
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_PROPERTY, &curVal);
+ // ResourceTypes
+ CborValue rtArray;
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_RESOURCE_TYPE, &rtArray);
+
+ CborValue rtVal;
+ err = err || cbor_value_enter_container(&rtArray, &rtVal);
+
+ OCStringLL* llPtr = NULL;
+ while(!err && cbor_value_is_text_string(&rtVal))
+ {
+ if(resource->types == NULL)
+ {
+ resource->types = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ llPtr = resource->types;
+ if(!llPtr)
+ {
+ OC_LOG_V(ERROR, TAG, "Memory allocation failed");
+ OICFree(resource->uri);
+ OICFree(resource->sid);
+ OICFree(resource);
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+ else
+ {
+ llPtr->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ llPtr = llPtr->next;
+ if(!llPtr)
+ {
+ OC_LOG_V(ERROR, TAG, "Memory allocation failed");
+ OICFree(resource->uri);
+ OICFree(resource->sid);
+ OCFreeOCStringLL(resource->types);
+ OICFree(resource);
+ return OC_STACK_NO_MEMORY;
+ }
+
+ }
+
+ err = err || cbor_value_dup_text_string(&rtVal, &(llPtr->value), &len, NULL);
+ err = err || cbor_value_advance(&rtVal);
+ }
+
+ err = err || cbor_value_leave_container(&rtArray, &rtVal);
+ //
+ // Interface Types
+ CborValue ifArray;
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_INTERFACE, &ifArray);
+ CborValue ifVal;
+ err = err || cbor_value_enter_container(&ifArray, &ifVal);
+
+ llPtr = NULL;
+ while(!err && cbor_value_is_text_string(&ifVal))
+ {
+ if(resource->interfaces == NULL)
+ {
+ resource->interfaces = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ llPtr = resource->interfaces;
+ if(!llPtr)
+ {
+ OC_LOG_V(ERROR, TAG, "Memory allocation failed");
+ OICFree(resource->uri);
+ OICFree(resource->sid);
+ OCFreeOCStringLL(resource->types);
+ OICFree(resource);
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+ else
+ {
+ llPtr->next = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ llPtr = llPtr->next;
+ if(!llPtr)
+ {
+ OC_LOG_V(ERROR, TAG, "Memory allocation failed");
+ OICFree(resource->uri);
+ OICFree(resource->sid);
+ OCFreeOCStringLL(resource->types);
+ OCFreeOCStringLL(resource->interfaces);
+ OICFree(resource);
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+
+ err = err || cbor_value_dup_text_string(&ifVal, &(llPtr->value), &len, NULL);
+ err = err || cbor_value_advance(&ifVal);
+ }
+ err = err || cbor_value_leave_container(&ifArray, &ifVal);
+
+ // Policy
+ {
+ CborValue policyMap;
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_POLICY, &policyMap);
+
+ // Bitmap
+ CborValue val;
+ err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &val);
+ uint64_t temp = 0;
+ err = err || cbor_value_get_uint64(&val, &temp);
+ resource->bitmap = (uint8_t)temp;
+ // Secure Flag
+ err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &val);
+ if(cbor_value_is_valid(&val))
+ {
+ err = err || cbor_value_get_boolean(&val, &(resource->secure));
+ // Port
+ CborValue port;
+ err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT,
+ &port);
+ if(cbor_value_is_valid(&port))
+ {
+ err = err || cbor_value_get_uint64(&port, &temp);
+ resource->port = (uint16_t)temp;
+ }
+ }
+ }
+ }
+
+ err = err || cbor_value_advance(arrayVal);
+ if(err)
+ {
+ OICFree(resource->uri);
+ OICFree(resource->sid);
+ OCFreeOCStringLL(resource->types);
+ OCFreeOCStringLL(resource->interfaces);
+ OICFree(resource);
+ OCDiscoveryPayloadDestroy(out);
+ OC_LOG_V(ERROR, TAG, "CBOR in error condition", err);
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+ ++resourceCount;
+ OCDiscoveryPayloadAddNewResource(out, resource);
+ }
+
+ *outPayload = (OCPayload*)out;
+
+ return OC_STACK_OK;
+}
+
+static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arrayVal)
+{
+ bool err = false;
+
+ if(cbor_value_is_map(arrayVal))
+ {
+ char* uri = NULL;
+ uint8_t* sid = NULL;
+ char* dname = NULL;
+ char* specVer = NULL;
+ char* dmVer = NULL;
+ CborValue curVal;
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
+ size_t len;
+ err = err || cbor_value_dup_text_string(&curVal, &uri, &len, NULL);
+
+ // Representation
+ {
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
+
+ CborValue repVal;
+ // Device ID
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DEVICE_ID, &repVal);
+ err = err || cbor_value_dup_byte_string(&repVal, &sid, &len, NULL);
+ // Device Name
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DEVICE_NAME, &repVal);
+ err = err || cbor_value_dup_text_string(&repVal, &dname, &len, NULL);
+ // Device Spec Version
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SPEC_VERSION, &repVal);
+ err = err || cbor_value_dup_text_string(&repVal, &specVer, &len, NULL);
+ // Data Model Version
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DATA_MODEL_VERSION, &repVal);
+ err = err || cbor_value_dup_text_string(&repVal, &dmVer, &len, NULL);
+
+ }
+
+ err = err || cbor_value_advance(arrayVal);
+
+ if(err)
+ {
+ OICFree(uri);
+ OICFree(sid);
+ OICFree(dname);
+ OICFree(specVer);
+ OICFree(dmVer);
+ OC_LOG_V(ERROR, TAG, "CBOR in error condition %d", err);
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+
+ *outPayload = (OCPayload*)OCDevicePayloadCreate(uri, sid, dname, specVer, dmVer);
+
+ OICFree(uri);
+ OICFree(sid);
+ OICFree(dname);
+ OICFree(specVer);
+ OICFree(dmVer);
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ return OC_STACK_OK;
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, PCF("Root device node was not a map"));
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+
+}
+
+static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* arrayVal)
+{
+ bool err = false;
+
+ if(cbor_value_is_map(arrayVal))
+ {
+ char* uri = NULL;
+ OCPlatformInfo info = {};
+ CborValue curVal;
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
+ size_t len;
+ err = err || cbor_value_dup_text_string(&curVal, &uri, &len, NULL);
+
+ // Representation
+ {
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
+
+ CborValue repVal;
+ // Platform ID
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_PLATFORM_ID, &repVal);
+ err = err || cbor_value_dup_text_string(&repVal, &(info.platformID), &len, NULL);
+
+ // MFG Name
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_NAME, &repVal);
+ err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerName), &len, NULL);
+
+ // MFG URL
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_URL, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerUrl), &len, NULL);
+ }
+
+ // Model Num
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MODEL_NUM, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.modelNumber), &len, NULL);
+ }
+
+ // Date of Mfg
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_DATE, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.dateOfManufacture), &len,
+ NULL);
+ }
+
+ // Platform Version
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_PLATFORM_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.platformVersion), &len,
+ NULL);
+ }
+
+ // OS Version
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_OS_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.operatingSystemVersion),
+ &len, NULL);
+ }
+
+ // Hardware Version
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_HARDWARE_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.hardwareVersion), &len,
+ NULL);
+ }
+
+ // Firmware Version
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_FIRMWARE_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.firmwareVersion), &len,
+ NULL);
+ }
+
+ // Support URL
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SUPPORT_URL, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.supportUrl), &len, NULL);
+ }
+
+ // System Time
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SYSTEM_TIME, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.systemTime), &len, NULL);
+ }
+ }
+
+ err = err || cbor_value_advance(arrayVal);
+
+ if(err)
+ {
+ OICFree(info.dateOfManufacture);
+ OICFree(info.firmwareVersion);
+ OICFree(info.hardwareVersion);
+ OICFree(info.manufacturerName);
+ OICFree(info.manufacturerUrl);
+ OICFree(info.modelNumber);
+ OICFree(info.operatingSystemVersion);
+ OICFree(info.platformID);
+ OICFree(info.platformVersion);
+ OICFree(info.supportUrl);
+ OICFree(info.systemTime);
+ OC_LOG(ERROR, TAG, PCF("CBOR error In ParsePlatformPayload"));
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+
+ *outPayload = (OCPayload*)OCPlatformPayloadCreateAsOwner(uri, &info);
+
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ return OC_STACK_OK;
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, PCF("Root device node was not a map"));
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+}
+
+static bool OCParseArray(OCRepPayload* out, const char* name, CborValue* container)
+{
+ CborValue insideArray;
+ bool err = false;
+ uint64_t tempInt = 0;
+ OCRepPayloadPropType type;
+ size_t dimensions[MAX_REP_ARRAY_DEPTH];
+ err = err || cbor_value_enter_container(container, &insideArray);
+
+ err = err || cbor_value_get_uint64(&insideArray, &tempInt);
+ err = err || cbor_value_advance_fixed(&insideArray);
+ type = (OCRepPayloadPropType)tempInt;
+
+ for(int i = 0; i < MAX_REP_ARRAY_DEPTH; ++ i)
+ {
+ err = err || cbor_value_get_uint64(&insideArray, &tempInt);
+ err = err || cbor_value_advance_fixed(&insideArray);
+ dimensions[i] = tempInt;
+ }
+
+ size_t dimTotal = calcDimTotal(dimensions);
+
+ void* arr = NULL;
+ char* tempStr;
+ size_t len;
+ OCRepPayload* pl;
+ switch(type)
+ {
+ case OCREP_PROP_INT:
+ arr = (int64_t*)OICMalloc(dimTotal * sizeof(int64_t));
+ for(size_t i = 0; i < dimTotal && !err; ++i)
+ {
+ err = err || cbor_value_get_int64(&insideArray, &(((int64_t*)arr)[i]));
+ err = err || cbor_value_advance_fixed(&insideArray);
+ }
+ if(!err &&
+ OCRepPayloadSetIntArrayAsOwner(out, name, (int64_t*)arr, dimensions))
+ {}
+ else
+ {
+ err = CborUnknownError;
+ }
+ break;
+ case OCREP_PROP_DOUBLE:
+ arr = (double*)OICMalloc(dimTotal * sizeof(double));
+ for(size_t i = 0; i < dimTotal && !err; ++i)
+ {
+ err = err || cbor_value_get_double(&insideArray, &(((double*)arr)[i]));
+ err = err || cbor_value_advance_fixed(&insideArray);
+ }
+ if(!err &&
+ OCRepPayloadSetDoubleArrayAsOwner(out, name, (double*)arr, dimensions))
+ {}
+ else
+ {
+ err = CborUnknownError;
+ }
+ break;
+ case OCREP_PROP_BOOL:
+ arr = (bool*)OICMalloc(dimTotal * sizeof(bool));
+ for(size_t i = 0; i < dimTotal && !err; ++i)
+ {
+ err = err || cbor_value_get_boolean(&insideArray, &(((bool*)arr)[i]));
+ err = err || cbor_value_advance_fixed(&insideArray);
+ }
+ if(!err &&
+ OCRepPayloadSetBoolArrayAsOwner(out, name, (bool*)arr, dimensions))
+ {}
+ else
+ {
+ err = CborUnknownError;
+ }
+ break;
+ case OCREP_PROP_STRING:
+ arr = (char**)OICMalloc(dimTotal * sizeof(char*));
+ for(size_t i = 0; i < dimTotal && !err; ++i)
+ {
+ err = err || cbor_value_dup_text_string(&insideArray, &tempStr,
+ &len, NULL);
+ ((char**)arr)[i] = tempStr;
+ }
+ if(!err &&
+ OCRepPayloadSetStringArrayAsOwner(out, name, (char**)arr, dimensions))
+ {}
+ else
+ {
+ err = CborUnknownError;
+ }
+ break;
+ case OCREP_PROP_OBJECT:
+ arr = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*));
+ for(size_t i = 0; i < dimTotal && !err; ++i)
+ {
+ pl = NULL;
+ err = err || OCParseSingleRepPayload(&pl, &insideArray);
+ ((OCRepPayload**)arr)[i] = pl;
+ err = err || cbor_value_advance(&insideArray);
+ }
+ if(!err &&
+ OCRepPayloadSetPropObjectArrayAsOwner(out, name, (OCRepPayload**)arr, dimensions))
+ {}
+ else
+ {
+ err = CborUnknownError;
+ }
+ break;
+ default:
+ OC_LOG(ERROR, TAG, "Invalid Array type in Parse Array");
+ err = CborUnknownError;
+ break;
+ }
+
+ return err;
+}
+
+static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue* repParent)
+{
+ *outPayload = OCRepPayloadCreate();
+ OCRepPayload* curPayload = *outPayload;
+ bool err = false;
+ if(!*outPayload)
+ {
+ return CborErrorOutOfMemory;
+ }
+
+ size_t len;
+ CborValue curVal;
+ err = err || cbor_value_map_find_value(repParent, OC_RSRVD_HREF, &curVal);
+ if(cbor_value_is_valid(&curVal))
+ {
+ err = err || cbor_value_dup_text_string(&curVal, &curPayload->uri, &len,
+ NULL);
+ }
+
+ err = err || cbor_value_map_find_value(repParent, OC_RSRVD_PROPERTY, &curVal);
+ if(cbor_value_is_valid(&curVal))
+ {
+ CborValue insidePropArray;
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_RESOURCE_TYPE,
+ &insidePropArray);
+
+ if(cbor_value_is_array(&insidePropArray))
+ {
+ CborValue rtArray;
+ err = err || cbor_value_enter_container(&insidePropArray, &rtArray);
+
+ while(!err && cbor_value_is_valid(&rtArray))
+ {
+ char* curRt;
+ cbor_value_dup_text_string(&rtArray, &curRt, &len, NULL);
+ OCRepPayloadAddResourceTypeAsOwner(curPayload, curRt);
+ }
+
+ err = err || cbor_value_leave_container(&insidePropArray, &rtArray);
+ }
+
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_INTERFACE, &insidePropArray);
+
+ if(cbor_value_is_array(&insidePropArray))
+ {
+ CborValue ifArray;
+ err = err || cbor_value_enter_container(&insidePropArray, &ifArray);
+
+ while(!err && cbor_value_is_valid(&ifArray))
+ {
+ char* curIf;
+ err = err || cbor_value_dup_text_string(&ifArray, &curIf, &len, NULL);
+ OCRepPayloadAddInterfaceAsOwner(curPayload, curIf);
+ }
+
+ err = err || cbor_value_leave_container(&insidePropArray, &ifArray);
+ }
+ }
+ err = err || cbor_value_map_find_value(repParent, OC_RSRVD_REPRESENTATION, &curVal);
+ if(cbor_value_is_map(&curVal))
+ {
+ CborValue repMap;
+ err = err || cbor_value_enter_container(&curVal, &repMap);
+
+ while(!err && cbor_value_is_valid(&repMap))
+ {
+ char* name;
+ err = err || cbor_value_dup_text_string(&repMap, &name, &len, NULL);
+
+ err = err || cbor_value_advance(&repMap);
+
+ int64_t intval = 0;
+ bool boolval = false;
+ char* strval = NULL;
+ double doubleval = 0;
+ OCRepPayload* pl;
+
+ switch(cbor_value_get_type(&repMap))
+ {
+ case CborNullType:
+ OCRepPayloadSetNull(curPayload, name);
+ break;
+ case CborIntegerType:
+ err = err || cbor_value_get_int64(&repMap, &intval);
+ OCRepPayloadSetPropInt(curPayload, name, intval);
+ break;
+ case CborDoubleType:
+ err = err || cbor_value_get_double(&repMap, &doubleval);
+ OCRepPayloadSetPropDouble(curPayload, name, doubleval);
+ case CborBooleanType:
+ err = err || cbor_value_get_boolean(&repMap, &boolval);
+ OCRepPayloadSetPropBool(curPayload, name, boolval);
+ break;
+ case CborTextStringType:
+ err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
+ OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
+ break;
+ case CborMapType:
+ err = err || OCParseSingleRepPayload(&pl, &repMap);
+ OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
+ break;
+ case CborArrayType:
+ err = err || OCParseArray(curPayload, name, &repMap);
+ break;
+ default:
+ OC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type);
+ err = true;
+ }
+
+ err = err || cbor_value_advance(&repMap);
+ OICFree(name);
+ }
+ err = err || cbor_value_leave_container(&curVal, &repMap);
+ }
+
+ if(err)
+ {
+ OCRepPayloadDestroy(*outPayload);
+ }
+
+ return err;
+}
+static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* arrayVal)
+{
+ bool err = false;
+
+ OCRepPayload* rootPayload = NULL;
+ OCRepPayload* curPayload = NULL;
+ OCRepPayload* temp = NULL;
+ while(!err && cbor_value_is_map(arrayVal))
+ {
+ err = err || OCParseSingleRepPayload(&temp, arrayVal);
+
+ if(rootPayload == NULL)
+ {
+ rootPayload = temp;
+ curPayload = temp;
+ }
+ else
+ {
+ curPayload->next = temp;
+ curPayload = curPayload->next;
+ }
+
+
+ err = err || cbor_value_advance(arrayVal);
+ if(err)
+ {
+ OCRepPayloadDestroy(rootPayload);
+ OC_LOG_V(ERROR, TAG, PCF("CBOR error in ParseRepPayload"));
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+ }
+
+ *outPayload = (OCPayload*)rootPayload;
+
+ return OC_STACK_OK;
+}
+
+static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* arrayVal)
+{
+ bool err = false;
+ if(cbor_value_is_map(arrayVal))
+ {
+ uint64_t seqNum = 0;
+ uint64_t maxAge = 0;
+ OCPresenceTrigger trigger = OC_PRESENCE_TRIGGER_CREATE;
+ char* tempStr = NULL;
+ size_t len = 0;
+
+ CborValue curVal;
+ // Sequence Number
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_NONCE, &curVal);
+ err = err || cbor_value_get_uint64(&curVal, &seqNum);
+
+ // Max Age
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_TTL, &curVal);
+ err = err || cbor_value_get_uint64(&curVal, &maxAge);
+
+ // Trigger
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_TRIGGER, &curVal);
+ err = err || cbor_value_dup_text_string(&curVal, &tempStr, &len, NULL);
+ trigger = convertTriggerStringToEnum(tempStr);
+ OICFree(tempStr);
+ tempStr = NULL;
+
+ // Resource type name
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_RESOURCE_TYPE, &curVal);
+ if(cbor_value_is_valid(&curVal))
+ {
+ err = err || cbor_value_dup_text_string(&curVal, &tempStr, &len, NULL);
+ }
+
+ err = err || cbor_value_advance(arrayVal);
+
+ if(!err)
+ {
+ *outPayload = (OCPayload*)OCPresencePayloadCreate(seqNum, maxAge, trigger, tempStr);
+ }
+ OICFree(tempStr);
+
+ if(err)
+ {
+ OCPayloadDestroy(*outPayload);
+ OC_LOG_V(ERROR, TAG, PCF("CBOR error Parse Presence Payload"));
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+
+ if(!*outPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ return OC_STACK_OK;
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, PCF("Root presence node was not a map"));
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+}
#include "oic_string.h"
#include "logger.h"
#include "cJSON.h"
+#include "ocpayload.h"
#include "cacommon.h"
#include "cainterface.h"
static OCPlatformInfo savedPlatformInfo = {};
static OCDeviceInfo savedDeviceInfo = {};
-static const char * VIRTUAL_RSRCS[] =
-{
- "/oic/res",
- "/oic/d",
- "/oic/p",
- "/oic/res/types/d",
- #ifdef WITH_PRESENCE
- "/oic/ad"
- #endif
-};
-
//-----------------------------------------------------------------------------
// Default resource entity handler function
//-----------------------------------------------------------------------------
return ret;
}
-static char* GetJSONStringFromPlatformInfo(OCPlatformInfo info)
+/*
+ * Function will extract 0, 1 or 2 filters from query.
+ * More than 2 filters or unsupported filters will result in error.
+ * If both filters are of the same supported type, the 2nd one will be picked.
+ * Resource and device filters in the SAME query are NOT validated
+ * and resources will likely not clear filters.
+ */
+static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char **filterTwo)
{
- 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());
-
- if (!repObj)
- {
- return NULL;
- }
- if (info.platformID)
- {
- cJSON_AddItemToObject (repObj, OC_RSRVD_PLATFORM_ID,
- cJSON_CreateString(info.platformID));
- }
-
- if (info.manufacturerName)
- {
- 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));
- }
+ char *key = NULL;
+ char *value = NULL;
+ char *restOfQuery = NULL;
+ int numKeyValuePairsParsed = 0;
- 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 char* GetJSONStringFromDeviceInfo(OCDeviceInfo 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_DEVICE_URI)));
-
- cJSON_AddItemToObject (rootObj, OC_RSRVD_REPRESENTATION, repObj = cJSON_CreateObject());
-
- if (!repObj)
- {
- return NULL;
- }
-
- cJSON_AddItemToObject (repObj, OC_RSRVD_DEVICE_ID,
- cJSON_CreateString(OCGetServerInstanceIDString()));
-
- if (info.deviceName)
- {
- cJSON_AddItemToObject (repObj, OC_RSRVD_DEVICE_NAME,
- cJSON_CreateString(info.deviceName));
- }
-
- cJSON_AddItemToObject (repObj, OC_RSRVD_SPEC_VERSION,
- cJSON_CreateString(OC_SPEC_VERSION));
-
- cJSON_AddItemToObject (repObj, OC_RSRVD_DATA_MODEL_VERSION,
- cJSON_CreateString(OC_DATA_MODEL_VERSION));
-
- jsonEncodedInfo = cJSON_PrintUnformatted (rootObj);
-
- cJSON_Delete(rootObj);
-
- return jsonEncodedInfo;
-}
-
-static OCStackResult ValidateUrlQuery (char *url, char *query,
- uint8_t *filterOn, char **filterValue)
-{
- if(!filterOn || !filterValue)
- {
- return OC_STACK_INVALID_PARAM;
- }
+ *filterOne = NULL;
+ *filterTwo = NULL;
- char *filterParam = NULL;
+ OC_LOG_V(INFO, TAG, PCF("Received query %s for param extraction"), query);
- OC_LOG(INFO, TAG, PCF("Entering ValidateUrlQuery"));
- if (!url)
- {
- return OC_STACK_INVALID_URI;
- }
+ char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery);
- if (strcmp ((char *)url, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0 ||
- strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0 ||
- strcmp((char *)url, GetVirtualResourceUri(OC_PLATFORM_URI)) == 0)
+ while(keyValuePair)
{
- *filterOn = STACK_RES_DISCOVERY_NOFILTER;
- if (query && *query)
+ if (numKeyValuePairsParsed >= 2)
{
- char* strTokPtr = NULL;
- filterParam = strtok_r((char *)query, "=", &strTokPtr);
- *filterValue = strtok_r(NULL, " ", &strTokPtr);
-
- if (!(*filterValue) || ! filterParam)
- {
- return OC_STACK_INVALID_QUERY;
- }
- 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)
- {
- // Resource discovery with resource type filter
- *filterOn = STACK_RES_DISCOVERY_RT_FILTER;
- }
- else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0)
- {
- //Device ID filter
- *filterOn = STACK_DEVICE_DISCOVERY_DI_FILTER;
- }
- else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0)
- {
- //Device Name filter
- *filterOn = STACK_DEVICE_DISCOVERY_DN_FILTER;
- }
- else
- {
- // Other filter types not supported
- return OC_STACK_INVALID_QUERY;
- }
+ OC_LOG(ERROR, TAG, PCF("More than 2 queries params in URI."));
+ return OC_STACK_INVALID_QUERY;
}
- }
- #ifdef WITH_PRESENCE
- 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
- {
- // Other URIs not yet supported
- return OC_STACK_INVALID_URI;
- }
- OC_LOG(INFO, TAG, PCF("Exiting ValidateUrlQuery"));
- return OC_STACK_OK;
-}
-
-OCStackResult
-BuildVirtualResourceResponse(const OCResource *resourcePtr, uint8_t filterOn,
- const char *filterValue, char *out, uint16_t *remaining,
- CATransportAdapter_t adapter)
-{
- if(!resourcePtr || !out || !remaining)
- {
- return OC_STACK_INVALID_PARAM;
- }
-
- OCResourceType *resourceTypePtr = NULL;
- OCResourceInterface *interfacePtr = NULL;
- cJSON *resObj = NULL;
- cJSON *propObj = NULL;
- cJSON *policyObj = NULL;
- cJSON *rtArray = NULL;
- char *jsonStr = NULL;
- uint8_t encodeRes = 0;
- OCStackResult ret = OC_STACK_OK;
- uint16_t jsonLen = 0;
+ key = strtok_r(keyValuePair, OC_KEY_VALUE_DELIMITER, &value);
- OC_LOG(INFO, TAG, PCF("Entering BuildVirtualResourceResponse"));
- resObj = cJSON_CreateObject();
-
- if (resourcePtr)
- {
- encodeRes = 0;
- if ((filterOn == STACK_RES_DISCOVERY_RT_FILTER) && filterValue)
+ if (!key || !value)
{
- resourceTypePtr = resourcePtr->rsrcType;
- while (resourceTypePtr)
- {
- if (strcmp (resourceTypePtr->resourcetypename, filterValue) == 0)
- {
- encodeRes = 1;
- break;
- }
- resourceTypePtr = resourceTypePtr->next;
- }
+ return OC_STACK_INVALID_QUERY;
}
- else if ((filterOn == STACK_RES_DISCOVERY_IF_FILTER) && filterValue)
+ else if (strcmp (key, OC_RSRVD_INTERFACE) == 0)
{
- interfacePtr = resourcePtr->rsrcInterface;
- while (interfacePtr)
- {
- if (strcmp (interfacePtr->name, filterValue) == 0)
- {
- encodeRes = 1;
- break;
- }
- interfacePtr = interfacePtr->next;
- }
+ *filterOne = value; // if
}
- else if (filterOn == STACK_RES_DISCOVERY_NOFILTER)
+ else if (strcmp (key, OC_RSRVD_RESOURCE_TYPE) == 0)
{
- encodeRes = 1;
+ *filterTwo = value; // rt
}
else
{
- //TODO: Unsupported query filter
+ OC_LOG_V(ERROR, TAG, "Unsupported query key: %s", key);
return OC_STACK_INVALID_QUERY;
}
+ ++numKeyValuePairsParsed;
- if (encodeRes)
- {
- // Add URIs
- cJSON_AddItemToObject(resObj, OC_RSRVD_HREF, cJSON_CreateString(resourcePtr->uri));
-
- // 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)
- {
- cJSON_AddItemToArray(rtArray,
- cJSON_CreateString(resourceTypePtr->resourcetypename));
- resourceTypePtr = resourceTypePtr->next;
- }
- // Add interface types
- cJSON_AddItemToObject(propObj, OC_RSRVD_INTERFACE, rtArray = cJSON_CreateArray());
- interfacePtr = resourcePtr->rsrcInterface;
- while (interfacePtr)
- {
- cJSON_AddItemToArray(rtArray, cJSON_CreateString(interfacePtr->name));
- interfacePtr = interfacePtr->next;
- }
-
- //Add Policy
- cJSON_AddItemToObject(propObj, OC_RSRVD_POLICY, policyObj = cJSON_CreateObject());
-
- if (policyObj)
- {
- // Policy Property Bitmap
- // If resource is discoverable, set discoverability flag.
- // Resources that are not discoverable will not have the flag.
- cJSON_AddNumberToObject(policyObj, OC_RSRVD_BITMAP,
- resourcePtr->resourceProperties & (OC_OBSERVABLE|OC_DISCOVERABLE));
-
- // Set secure flag for secure resources
- if (resourcePtr->resourceProperties & OC_SECURE)
- {
- cJSON_AddNumberToObject(policyObj, OC_RSRVD_SECURE, OC_RESOURCE_SECURE);
- //Set the IP port also as secure resources are hosted on a different port
- uint16_t port = 0;
- if (GetSecurePortInfo(adapter, &port) == OC_STACK_OK)
- {
- cJSON_AddNumberToObject(policyObj, OC_RSRVD_HOSTING_PORT, port);
- }
- }
- }
- else
- {
- cJSON_Delete(resObj);
- return OC_STACK_NO_MEMORY;
- }
- }
+ keyValuePair = strtok_r(NULL, OC_QUERY_SEPARATOR, &restOfQuery);
}
- jsonStr = cJSON_PrintUnformatted (resObj);
- if(!jsonStr)
- {
- cJSON_Delete(resObj);
- return OC_STACK_NO_MEMORY;
- }
+ OC_LOG_V(INFO, TAG, "Extracted params %s and %s.", *filterOne, *filterTwo);
+ return OC_STACK_OK;
+}
- jsonLen = strlen(jsonStr);
- if (jsonLen < *remaining)
+static OCVirtualResources GetTypeOfVirtualURI(const char *uriInRequest)
+{
+ if (strcmp(uriInRequest, OC_RSRVD_WELL_KNOWN_URI) == 0)
{
- OICStrcpy(out, *remaining, jsonStr);
- *remaining = *remaining - jsonLen;
+ return OC_WELL_KNOWN_URI;
}
- else
+ else if (strcmp(uriInRequest, OC_RSRVD_DEVICE_URI) == 0)
{
- ret = OC_STACK_ERROR;
+ return OC_DEVICE_URI;
}
- cJSON_Delete (resObj);
- OICFree (jsonStr);
-
- OC_LOG(INFO, TAG, PCF("Exiting BuildVirtualResourceResponse"));
- return ret;
-}
-
-OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filterValue,
- char *out, uint16_t *remaining)
-{
- if(!out || !remaining)
+ else if (strcmp(uriInRequest, OC_RSRVD_PLATFORM_URI) == 0)
{
- return OC_STACK_INVALID_PARAM;
+ return OC_PLATFORM_URI;
}
-
- OCStackResult ret = OC_STACK_ERROR;
- char *jsonStr = NULL;
- uint16_t jsonLen = 0;
-
- jsonStr = GetJSONStringFromDeviceInfo(savedDeviceInfo);
-
- if(jsonStr)
+ else if (strcmp(uriInRequest, OC_RSRVD_RESOURCE_TYPES_URI) == 0)
{
- jsonLen = strlen(jsonStr);
-
- if (jsonLen < *remaining)
- {
- OICStrcpy(out, *remaining, jsonStr);
- *remaining = *remaining - jsonLen;
- ret = OC_STACK_OK;
- }
- else
- {
- ret = OC_STACK_ERROR;
- }
-
- OICFree(jsonStr);
+ return OC_RESOURCE_TYPES_URI;
}
- else
+#ifdef WITH_PRESENCE
+ else if (strcmp(uriInRequest, OC_RSRVD_PRESENCE_URI) == 0)
{
- OC_LOG(ERROR, TAG, PCF("Error encoding save device info."));
- ret = OC_STACK_ERROR;
+ return OC_PRESENCE;
}
- return ret;
+#endif //WITH_PRESENCE
+ return OC_UNKNOWN_URI;
}
-OCStackResult BuildVirtualResourceResponseForPlatform(char *out, uint16_t *remaining)
+static OCStackResult getQueryParamsForFiltering (OCVirtualResources uri, char *query,
+ char **filterOne, char **filterTwo)
{
- OCStackResult ret = OC_STACK_OK;
-
- char *jsonStr = GetJSONStringFromPlatformInfo(savedPlatformInfo);
-
- if(jsonStr)
+ if(!filterOne || !filterTwo)
{
- size_t jsonLen = strlen(jsonStr);
-
- if (jsonLen < *remaining)
- {
- OICStrcpy(out, *remaining, jsonStr);
- *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;
- }
- OICFree(jsonStr);
+ return OC_STACK_INVALID_PARAM;
}
- else
+
+ *filterOne = NULL;
+ *filterTwo = NULL;
+
+ #ifdef WITH_PRESENCE
+ if (uri == OC_PRESENCE)
{
- OC_LOG(ERROR, TAG, PCF("Error encoding save platform info."));
- ret = OC_STACK_ERROR;
+ //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 for virtual resource."));
+ return OC_STACK_OK;
}
+ #endif
+ OCStackResult result = OC_STACK_OK;
- return ret;
-
-}
-const char * GetVirtualResourceUri( OCVirtualResources resource)
-{
- if (resource < OC_MAX_VIRTUAL_RESOURCES)
+ if (query && *query)
{
- return VIRTUAL_RSRCS[resource];
+ result = ExtractFiltersFromQuery(query, filterOne, filterTwo);
}
- return NULL;
+ return result;
}
-bool IsVirtualResource(const char* resourceUri)
+OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
+ OCDiscoveryPayload* payload, CATransportAdapter_t adapter )
{
- if(!resourceUri)
+ if (!resourcePtr || !payload)
{
- return false;
+ return OC_STACK_INVALID_PARAM;
}
-
- for (int i = 0; i < OC_MAX_VIRTUAL_RESOURCES; i++)
+ uint16_t port = 0;
+ if (resourcePtr->resourceProperties & OC_SECURE)
{
- if (strcmp(resourceUri, GetVirtualResourceUri((OCVirtualResources)i)) == 0)
- {
- return true;
- }
+ if(GetSecurePortInfo (adapter, &port) != OC_STACK_OK)
+ {
+ port = 0;
+ }
}
- return false;
+
+ OCDiscoveryPayloadAddResource(payload, resourcePtr, port);
+ return OC_STACK_OK;
}
+
uint8_t IsCollectionResource (OCResource *resource)
{
if(!resource)
const OCDevAddr *devAddr = &request->devAddr;
// Check if virtual resource
- if (IsVirtualResource((const char*)request->resourceUrl))
+ if (GetTypeOfVirtualURI(request->resourceUrl) != OC_UNKNOWN_URI)
{
*handling = OC_RESOURCE_VIRTUAL;
*resource = headResource;
return result;
}
-static OCStackResult
-HandleVirtualResource(OCServerRequest *request, OCResource *resource)
+static bool resourceMatchesRTFilter(OCResource *resource, char *resourceTypeFilter)
{
- if (!request || !resource)
+ if (!resource)
{
- return OC_STACK_INVALID_PARAM;
+ return false;
}
- OCStackResult result = OC_STACK_ERROR;
- char *filterValue = NULL;
- uint8_t filterOn = 0;
- uint16_t remaining = 0;
- char * ptr = NULL;
- uint8_t firstLoopDone = 0;
- char discoveryResBuf[MAX_RESPONSE_LENGTH] = {};
-
- OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource"));
+ // Null or empty is analogous to no filter.
+ if (resourceTypeFilter == NULL || *resourceTypeFilter == 0)
+ {
+ return true;
+ }
- result = ValidateUrlQuery (request->resourceUrl,
- request->query, &filterOn,
- &filterValue);
+ OCResourceType *resourceTypePtr = resource->rsrcType;
- if (result == OC_STACK_OK)
+ while (resourceTypePtr)
{
- if (strcmp ((char *)request->resourceUrl, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0)
+ if (strcmp (resourceTypePtr->resourcetypename, resourceTypeFilter) == 0)
{
- ptr = discoveryResBuf;
- remaining = MAX_RESPONSE_LENGTH;
+ return true;
+ }
+ resourceTypePtr = resourceTypePtr->next;
+ }
- // 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))
- {
- // if there is data on the buffer, we have already added a response,
- // so we need to add a comma before we do anything
- if(firstLoopDone
- && remaining >= (sizeof(OC_JSON_SEPARATOR)+1))
- {
- *ptr = OC_JSON_SEPARATOR;
- ptr++;
- remaining--;
- }
- firstLoopDone = 1;
- result = BuildVirtualResourceResponse(resource, filterOn,
- filterValue, (char*)ptr, &remaining,
- (CATransportAdapter_t)request->devAddr.adapter);
-
- if (result != OC_STACK_OK)
- {
- // if this failed, we need to remove the comma added above.
- if(firstLoopDone)
- {
- ptr--;
- *ptr = '\0';
- remaining++;
- }
- break;
- }
- ptr += strlen((char *)ptr);
- }
- resource = resource->next;
- }
+ OC_LOG_V(INFO, TAG, PCF("%s does not contain rt=%s."), resource->uri, resourceTypeFilter);
+ return false;
+}
- if(strlen((const char *)discoveryResBuf) > 0)
- {
- OCEntityHandlerResponse response = {};
+static bool resourceMatchesIFFilter(OCResource *resource, char *interfaceFilter)
+{
+ if (!resource)
+ {
+ return false;
+ }
+
+ // Null or empty is analogous to no filter.
+ if (interfaceFilter == NULL || *interfaceFilter == 0)
+ {
+ return true;
+ }
- 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;
+ OCResourceInterface *interfacePtr = resource->rsrcInterface;
- result = OCDoResponse(&response);
- }
- }
- else if (strcmp ((char *)request->resourceUrl, GetVirtualResourceUri(OC_DEVICE_URI)) == 0)
+ while (interfacePtr)
+ {
+ if (strcmp (interfacePtr->name, interfaceFilter) == 0)
{
- remaining = MAX_RESPONSE_LENGTH;
- ptr = discoveryResBuf;
+ return true;
+ }
+ interfacePtr = interfacePtr->next;
+ }
- result = BuildVirtualResourceResponseForDevice(filterOn, filterValue,
- (char*)ptr, &remaining);
+ OC_LOG_V(INFO, TAG, PCF("%s does not contain if=%s."), resource->uri, interfaceFilter);
+ return false;
+}
- if(result == OC_STACK_OK)
- {
- ptr += strlen((char*)ptr);
- }
+/*
+ * If the filters are null, they will be assumed to NOT be present
+ * and the resource will not be matched against them.
+ * Function will return true if all non null AND non empty filters passed in find a match.
+ */
+static bool includeThisResourceInResponse(OCResource *resource,
+ char *interfaceFilter,
+ char *resourceTypeFilter)
+{
+ if (!resource)
+ {
+ OC_LOG(ERROR, TAG, PCF("Invalid resource"));
+ return false;
+ }
- if(remaining < MAX_RESPONSE_LENGTH)
- {
- OCEntityHandlerResponse response = {0};
+ if ( !(resource->resourceProperties & OC_ACTIVE) ||
+ !(resource->resourceProperties & OC_DISCOVERABLE))
+ {
+ OC_LOG_V(INFO, TAG, PCF("%s not ACTIVE or DISCOVERABLE"), resource->uri);
+ return false;
+ }
- 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;
+ return resourceMatchesIFFilter(resource, interfaceFilter) &&
+ resourceMatchesRTFilter(resource, resourceTypeFilter);
- result = OCDoResponse(&response);
- }
+}
+
+OCStackResult SendNonPersistantDiscoveryResponse(OCServerRequest *request, OCResource *resource,
+ OCPayload *discoveryPayload)
+{
+ OCEntityHandlerResponse response = {};
+
+ response.ehResult = OC_EH_OK;
+ response.payload = discoveryPayload;
+ response.persistentBufferFlag = 0;
+ response.requestHandle = (OCRequestHandle) request;
+ response.resourceHandle = (OCResourceHandle) resource;
+
+ return OCDoResponse(&response);
+}
+
+static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
+{
+ if (!request || !resource)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult discoveryResult = OC_STACK_ERROR;
+ OCPayload* payload = NULL;
+ char *filterOne = NULL;
+ char *filterTwo = NULL;
+
+ OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource"));
+
+ OCVirtualResources virtualUriInRequest = GetTypeOfVirtualURI (request->resourceUrl);
+
+
+ if (virtualUriInRequest == OC_WELL_KNOWN_URI)
+ {
+ discoveryResult = getQueryParamsForFiltering (virtualUriInRequest, request->query,
+ &filterOne, &filterTwo);
+ if (discoveryResult != OC_STACK_OK)
+ {
+ OC_LOG_V(ERROR, TAG, "Error (%d) validating query.\n", discoveryResult);
+ return discoveryResult;
}
- else if (strcmp ((char *)request->resourceUrl, GetVirtualResourceUri(OC_PLATFORM_URI)) == 0)
+ payload = (OCPayload*)OCDiscoveryPayloadCreate();
+
+ if(!payload)
{
- remaining = MAX_RESPONSE_LENGTH;
- ptr = discoveryResBuf;
+ return OC_STACK_NO_MEMORY;
+ }
- result = BuildVirtualResourceResponseForPlatform((char*)ptr, &remaining);
- if(result == OC_STACK_OK)
+ for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
+ {
+ if(includeThisResourceInResponse(resource, filterOne, filterTwo))
{
- ptr += strlen((char*)ptr);
+ discoveryResult = BuildVirtualResourceResponse(resource,
+ (OCDiscoveryPayload*)payload,
+ (CATransportAdapter_t)request->devAddr.adapter);
}
-
- if(remaining < MAX_RESPONSE_LENGTH)
+ }
+ }
+ else if (virtualUriInRequest == OC_DEVICE_URI)
+ {
+ payload = (OCPayload*)OCDevicePayloadCreate(OC_RSRVD_DEVICE_URI,
+ OCGetServerInstanceID(), savedDeviceInfo.deviceName,
+ OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
+ if (!payload)
{
- OCEntityHandlerResponse response = {0};
+ discoveryResult = OC_STACK_NO_MEMORY;
+ }
+ }
+ else if (virtualUriInRequest == OC_PLATFORM_URI)
+ {
+ OCPlatformPayload* payload = OCPlatformPayloadCreate(
+ OC_RSRVD_PLATFORM_URI,
+ &savedPlatformInfo);
+ if (!payload)
+ {
+ discoveryResult = OC_STACK_NO_MEMORY;
+ }
+ }
- 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;
+ #ifdef WITH_PRESENCE
+ else
+ {
+ if(resource->resourceProperties & OC_ACTIVE)
+ {
+ discoveryResult = SendPresenceNotification(resource->rsrcType,
+ OC_PRESENCE_TRIGGER_CHANGE);
+ }
+ }
+ #endif
- result = OCDoResponse(&response);
- }
+ // Presence uses observer notification api to respond via SendPresenceNotification.
+ if (virtualUriInRequest != OC_PRESENCE)
+ {
+ if(discoveryResult == OC_STACK_OK)
+ {
+ discoveryResult = SendNonPersistantDiscoveryResponse(request, resource,
+ payload);
+ OCPayloadDestroy(payload);
}
- #ifdef WITH_PRESENCE
else
{
- if(resource->resourceProperties & OC_ACTIVE){
- SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
- }
+ OC_LOG_V(ERROR, TAG, "Error (%d) building (%d) discovery response. "\
+ "Not responding to request.", discoveryResult, virtualUriInRequest);
}
- #endif
}
- result = OC_STACK_OK;
- return result;
+
+ return discoveryResult;
}
static OCStackResult
OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithDefaultDeviceEntityHandler"));
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
request->method, (OCResourceHandle) NULL, request->query,
- request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
+ request->payload, request->payloadSize,
+ request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
(OCObserveAction)request->observationOption, (OCObservationId)0);
VERIFY_SUCCESS(result, OC_STACK_OK);
OCEntityHandlerRequest ehRequest = {};
OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithEntityHandler"));
+
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
request->method, (OCResourceHandle) resource, request->query,
- request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
+ request->payload, request->payloadSize, request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
(OCObserveAction)request->observationOption, 0);
VERIFY_SUCCESS(result, OC_STACK_OK);
OC_LOG(INFO, TAG, PCF("No observation requested"));
ehFlag = OC_REQUEST_FLAG;
}
- else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER &&
- !collectionResource)
+ else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && !collectionResource)
{
- OC_LOG(INFO, TAG, PCF("Registering observation requested"));
+ OC_LOG(INFO, TAG, PCF("Observation registration requested"));
+
result = GenerateObserverId(&ehRequest.obsInfo.obsId);
VERIFY_SUCCESS(result, OC_STACK_OK);
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.
+
+ // 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(ERROR, TAG, PCF("Observer Addition failed"));
ehFlag = OC_REQUEST_FLAG;
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
request->method, (OCResourceHandle) resource, request->query,
- request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
+ request->payload, request->payloadSize, request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
(OCObserveAction)request->observationOption, (OCObservationId) 0);
if(result != OC_STACK_OK)
#include "ocresourcehandler.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
#include "cacommon.h"
#include "cainterface.h"
serverResponse = (OCServerResponse *) OICCalloc(1, sizeof(OCServerResponse));
VERIFY_NON_NULL(serverResponse);
- serverResponse->payload = (char *) OICCalloc(1, MAX_RESPONSE_LENGTH);
- VERIFY_NON_NULL(serverResponse->payload);
+ serverResponse->payload = NULL;
- serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
serverResponse->requestHandle = requestHandle;
*response = serverResponse;
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 notificationFlag, OCMethod method,
uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
OCQualityOfService qos, char * query,
OCHeaderOption * rcvdVendorSpecificHeaderOptions,
- char * reqJSONPayload, CAToken_t requestToken, uint8_t tokenLength,
+ uint8_t * payload, CAToken_t requestToken, uint8_t tokenLength,
char * resourceUrl, size_t reqTotalSize, const OCDevAddr *devAddr)
{
OCServerRequest * serverRequest = NULL;
- //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 *) OICCalloc(1, sizeof(OCServerRequest) +
(reqTotalSize ? reqTotalSize : 1) - 1);
VERIFY_NON_NULL(devAddr);
memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions,
MAX_HEADER_OPTIONS * sizeof(OCHeaderOption));
}
- if(reqJSONPayload && reqTotalSize)
+ if(payload && reqTotalSize)
{
- OICStrcpy(serverRequest->reqJSONPayload, reqTotalSize, reqJSONPayload);
+ // destination is at least 1 greater than the source, so a NULL always exists in the
+ // last character
+ memcpy(serverRequest->payload, payload, reqTotalSize);
+ serverRequest->payloadSize = reqTotalSize;
}
+
serverRequest->requestComplete = 0;
if(requestToken)
{
return OC_STACK_NO_MEMORY;
}
-/**
- * Form the OCEntityHandlerRequest struct that is passed to a resource's entity handler
- *
- * @param entityHandlerRequest - pointer to the OCEntityHandlerRequest struct that is created.
- * Required to be zero-initialized before calling this function.
- * @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 * payload,
+ size_t payloadSize,
uint8_t numVendorOptions,
OCHeaderOption * vendorOptions,
OCObserveAction observeAction,
entityHandlerRequest->query = queryBuf;
entityHandlerRequest->obsInfo.action = observeAction;
entityHandlerRequest->obsInfo.obsId = observeID;
+
+ if(payload && payloadSize)
+ {
+ if(OCParsePayload(&entityHandlerRequest->payload, payload, payloadSize) != OC_STACK_OK)
+ {
+ return OC_STACK_ERROR;
+ }
+ }
+ else
+ {
+ entityHandlerRequest->payload = NULL;
+ }
+
entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
- entityHandlerRequest->reqJSONPayload = bufReqPayload;
return OC_STACK_OK;
}
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;
CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
responseInfo.info.options = NULL;
}
- char payload[MAX_RESPONSE_LENGTH + OC_JSON_PREFIX_LEN + OC_JSON_SUFFIX_LEN + 1] = {};
-
// Put the JSON prefix and suffix around the payload
- OICStrcpy(payload, sizeof(payload), OC_JSON_PREFIX);
- if(ehResponse->payloadSize)
+ if(ehResponse->payload)
{
- OICStrcatPartial(payload, sizeof(payload),
- ehResponse->payload,
- ehResponse->payloadSize < MAX_RESPONSE_LENGTH ?
- ehResponse->payloadSize : MAX_RESPONSE_LENGTH);
+ OCStackResult result;
+ if((result = OCConvertPayload(ehResponse->payload, &responseInfo.info.payload,
+ &responseInfo.info.payloadSize))
+ != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "Error converting payload");
+ return result;
+ }
+
+ if(responseInfo.info.payloadSize > MAX_RESPONSE_LENGTH)
+ {
+ OICFree(responseInfo.info.payload);
+ OC_LOG(ERROR, TAG, "Payload too long!");
+ return OC_STACK_INVALID_PARAM;
+ }
+ }
+ else
+ {
+ responseInfo.info.payload = NULL;
+ responseInfo.info.payloadSize = 0;
}
- OICStrcat(payload, sizeof(payload), OC_JSON_SUFFIX);
- responseInfo.info.payload = (CAPayload_t)payload;
#ifdef WITH_PRESENCE
//TODO: Add other connectivity types to CAConnTypes[] when enabled
CATransportAdapter_t CAConnTypes[] = {CA_ADAPTER_IP};
- const char * connTypes[] = {"ip transport"};
+ const char * connTypes[] = {"IP"};
int size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
CATransportAdapter_t adapter = responseEndpoint.adapter;
CAResult_t caResult = CA_STATUS_FAILED;
result = OC_STACK_OK;
- //Sending response on all n/w interfaces
+ // Default adapter, try to send response out on all adapters.
+ if (adapter == CA_DEFAULT_ADAPTER)
+ {
+ adapter =
+ (CATransportAdapter_t)(CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE | CA_ADAPTER_RFCOMM_BTEDR);
+ }
+
for(int i = 0; i < size; i++ )
{
responseEndpoint.adapter = (CATransportAdapter_t)(adapter & CAConnTypes[i]);
}
#endif
+ OICFree(responseInfo.info.payload);
OICFree(responseInfo.info.token);
OICFree(responseInfo.info.options);
//Delete the request
OCStackResult stackRet = OC_STACK_ERROR;
OCServerRequest * serverRequest = NULL;
OCServerResponse * serverResponse = NULL;
- uint16_t bufferNeeded = 0;
if(!ehResponse || !ehResponse->payload)
{
return OC_STACK_INVALID_PARAM;
}
- OC_LOG_V(INFO, TAG, "Inside HandleAggregateResponse: %s", ehResponse->payload);
+ OC_LOG(INFO, TAG, "Inside HandleAggregateResponse");
serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
serverResponse = GetServerResponseUsingHandle((OCServerRequest *)ehResponse->requestHandle);
return stackRet;
}
VERIFY_NON_NULL(serverResponse);
- VERIFY_NON_NULL(serverResponse->payload);
}
- // 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)
- {
- bufferNeeded += strlen(OC_JSON_SEPARATOR_STR);
- }
- if(serverResponse->remainingPayloadSize >= bufferNeeded)
+ if(serverResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION ||
+ ehResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION)
{
- OC_LOG(ERROR, TAG, PCF("There is room in response buffer"));
- // append
- // allocated size of the payload is assumed, since a search of the code
- // shows that it is OICCalloc'ed to this size in AddServerResponse above
- OICStrcatPartial(serverResponse->payload,
- MAX_RESPONSE_LENGTH,
- ehResponse->payload,
- serverResponse->remainingPayloadSize);
- OC_LOG_V(INFO, TAG, "Current aggregated response ...%s", serverResponse->payload);
- serverResponse->remainingPayloadSize -= strlen((char *)ehResponse->payload);
- (serverRequest->numResponses)--;
- if(serverRequest->numResponses == 0)
- {
- OC_LOG(INFO, TAG, PCF("This is the last response fragment"));
- ehResponse->payload = serverResponse->payload;
- ehResponse->payloadSize = strlen((char *) serverResponse->payload) + 1;
- stackRet = HandleSingleResponse(ehResponse);
- //Delete the request and response
- FindAndDeleteServerRequest(serverRequest);
- FindAndDeleteServerResponse(serverResponse);
- }
- else
- {
- OC_LOG(INFO, TAG, PCF("More response fragments to come"));
- OICStrcatPartial(serverResponse->payload,
- MAX_RESPONSE_LENGTH,
- OC_JSON_SEPARATOR_STR,
- serverResponse->remainingPayloadSize);
- OC_LOG_V(INFO, TAG, "Current aggregated response ...%s", serverResponse->payload);
- serverResponse->remainingPayloadSize -= strlen(OC_JSON_SEPARATOR_STR);
- stackRet = OC_STACK_OK;
- }
+ stackRet = OC_STACK_ERROR;
+ OC_LOG(ERROR, TAG, PCF("Error adding payload, as it was the incorrect type"));
+ goto exit;
}
- else
+
+ OCRepPayloadAppend((OCRepPayload*)serverResponse->payload,
+ (OCRepPayload*)ehResponse->payload);
+
+ (serverRequest->numResponses)--;
+
+ if(serverRequest->numResponses == 0)
{
- OC_LOG(ERROR, TAG, PCF("No room in response buffer"));
+ OC_LOG(INFO, TAG, PCF("This is the last response fragment"));
+ ehResponse->payload = serverResponse->payload;
+ stackRet = HandleSingleResponse(ehResponse);
//Delete the request and response
FindAndDeleteServerRequest(serverRequest);
FindAndDeleteServerResponse(serverResponse);
- stackRet = OC_STACK_NO_MEMORY;
+ }
+ else
+ {
+ OC_LOG(INFO, TAG, PCF("More response fragments to come"));
+ stackRet = OC_STACK_OK;
}
}
exit:
#include "secureresourcemanager.h"
#include "cacommon.h"
#include "cainterface.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
#ifdef WITH_ARDUINO
#include "Time.h"
#include "coap_time.h"
#include "utlist.h"
#include "pdu.h"
-#include "cJSON.h"
#ifndef ARDUINO
#include <arpa/inet.h>
#define MAX_OBSERVE_AGE (0x2FFFFUL)
#define MILLISECONDS_PER_SECOND (1000)
-/**
- * Parse the presence payload and extract various parameters.
- * Note: Caller should invoke OICFree after done with resType pointer.
- *
- * @param payload Presence payload.
- * @param seqNum Sequence number.
- * @param maxAge Time To Live (in seconds).
- * @param resType Resource type.
- */
-void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge,
- OCPresenceTrigger *presenceTrigger, char** resType);
//-----------------------------------------------------------------------------
// Private internal function prototypes
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);
-
/*
* Attempts to initialize every network interface that the CA Layer might have compiled in.
*
if(observer)
{
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
- OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
+ OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, 0,
NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
if(result != OC_STACK_OK)
{
if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
{
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
- OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
+ OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, 0,
NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
if(result != OC_STACK_OK)
{
{
CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
- // supply default behavior
+ // supply default behavior.
if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
{
caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
*
* requestUri must be a char array of size CA_MAX_URI_LENGTH
*/
-static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri, char *presenceUri)
+static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
+ char *presenceUri)
{
- VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
}
return snprintf(presenceUri, CA_MAX_URI_LENGTH, format, endpoint->addr,
- endpoint->port, OC_PRESENCE_URI);
+ endpoint->port, OC_RSRVD_PRESENCE_URI);
}
-void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge,
- OCPresenceTrigger *presenceTrigger, char** resType)
-{
- if(!payload || !seqNum || !maxAge || !presenceTrigger || !resType)
- {
- return;
- }
-
- cJSON *repObj = cJSON_Parse(payload);
- cJSON *ocObj = NULL;
- cJSON *presenceObj = NULL;
- cJSON *seqNumObj = NULL;
- cJSON *maxAgeObj = NULL;
- cJSON *triggerObj = NULL;
- cJSON *resObj = NULL;
- if(repObj)
- {
- ocObj = cJSON_GetObjectItem(repObj, OC_RSRVD_OC);
- if(ocObj)
- {
- //Presence payloads should only carry one JSON payload. The first
- // & only array item is retrieved.
- presenceObj = cJSON_GetArrayItem(ocObj, 0);
- if(presenceObj)
- {
- seqNumObj = cJSON_GetObjectItem(presenceObj, OC_RSRVD_NONCE);
- if(seqNumObj)
- {
- *seqNum = (uint32_t)seqNumObj->valuedouble;
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("Nonce (AKA SeqNum) not found in"
- " JSON Presence Payload."));
- goto exit;
- }
- maxAgeObj = cJSON_GetObjectItem(presenceObj, OC_RSRVD_TTL);
- if(maxAgeObj)
- {
- *maxAge = maxAgeObj->valueint;
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("TTL (AKA MaxAge) not found in"
- " JSON Presence Payload."));
- goto exit;
- }
- triggerObj = cJSON_GetObjectItem(presenceObj,
- OC_RSRVD_TRIGGER);
- if(triggerObj)
- {
- char * triggerStr = triggerObj->valuestring;
- *presenceTrigger = convertTriggerStringToEnum(triggerStr);
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("Trigger Reason not found in"
- " JSON Presence Payload."));
- goto exit;
- }
- resObj = cJSON_GetObjectItem(presenceObj,
- OC_RSRVD_RESOURCE_TYPE);
- if(resObj)
- {
- *resType = OICStrdup(resObj->valuestring);
- if(!*resType)
- {
- goto exit;
- }
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("Resource Type not found in"
- " JSON Presence Payload."));
- goto exit;
- }
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("JSON Presence Object not found in"
- " Presence Payload."));
- OICFree(*resType);
- goto exit;
- }
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("JSON Presence Payload does not contain a"
- " valid \"oic\" JSON representation."));
- OICFree(*resType);
- goto exit;
- }
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("JSON Presence Payload does map to a valid JSON"
- " representation."));
- OICFree(*resType);
- goto exit;
- }
-
-exit:
- cJSON_Delete(repObj);
-}
OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
const CAResponseInfo_t *responseInfo)
OCClientResponse response;
OCStackResult result = OC_STACK_ERROR;
uint32_t maxAge = 0;
- OCPresenceTrigger presenceTrigger = OC_PRESENCE_TRIGGER_CHANGE;
int uriLen;
char presenceUri[CA_MAX_URI_LENGTH];
return OC_STACK_ERROR;
}
- uriLen = FormCanonicalPresenceUri(endpoint, OC_PRESENCE_URI, presenceUri);
+ uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
if (uriLen < 0 || uriLen >= sizeof (presenceUri))
{
return OC_STACK_INVALID_URI;
}
else
{
- strncpy(presenceUri, responseInfo->info.resourceUri, CA_MAX_URI_LENGTH);
+ snprintf (presenceUri, MAX_URI_LENGTH, "coap://[%s]:%u%s", OC_MULTICAST_IP,
+ OC_MULTICAST_PORT, OC_RSRVD_PRESENCE_URI);
cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
if (cbNode)
{
goto exit;
}
- response.resJSONPayload = responseInfo->info.payload;
+ response.payload = NULL;
response.result = OC_STACK_OK;
CopyEndpointToDevAddr(endpoint, &response.devAddr);
if (responseInfo->info.payload)
{
- parsePresencePayload(responseInfo->info.payload,
- &(response.sequenceNumber),
- &maxAge,
- &presenceTrigger,
- &resourceTypeName);
+ result = OCParsePayload(&response.payload, responseInfo->info.payload,
+ responseInfo->info.payloadSize);
+
+ if(result != OC_STACK_OK || response.payload->type != PAYLOAD_TYPE_PRESENCE)
+ {
+ OC_LOG(ERROR, TAG, PCF("Presence parse failed"));
+ goto exit;
+ }
+ response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
+ resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
+ maxAge = ((OCPresencePayload*)response.payload)->maxAge;
}
if (presenceSubscribe)
cbNode->sequenceNumber = response.sequenceNumber;
// Ensure that a filter is actually applied.
- if(resourceTypeName && cbNode->filterResourceType)
+ if( resourceTypeName && cbNode->filterResourceType)
{
if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
{
VERIFY_NON_NULL_NR(endPoint, FATAL);
VERIFY_NON_NULL_NR(responseInfo, FATAL);
VERIFY_NON_NULL_NR(responseInfo->info.resourceUri, FATAL);
+ OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
- if(strcmp(responseInfo->info.resourceUri, OC_PRESENCE_URI) == 0)
+ if(strcmp(responseInfo->info.resourceUri, OC_RSRVD_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);
+ OC_LOG(DEBUG, TAG, PCF("Response has the token:"));
+ OC_LOG_BUFFER(DEBUG, TAG, (const uint8_t*)responseInfo->info.token, responseInfo->info.tokenLength);
ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
responseInfo->info.tokenLength);
response.resourceUri = responseInfo->info.resourceUri;
response.result = CAToOCStackResult(responseInfo->result);
- response.resJSONPayload = (const char*)responseInfo->info.payload;
+ if(responseInfo->info.payload &&
+ responseInfo->info.payloadSize &&
+ OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
+ responseInfo->info.payloadSize))
+ {
+ OC_LOG(ERROR, TAG, PCF("Error converting payload"));
+ return;
+ }
+
response.numRcvdVendorSpecificHeaderOptions = 0;
if(responseInfo->info.numOptions > 0)
{
cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
MILLISECONDS_PER_SECOND);
}
+ OCPayloadDestroy(response.payload);
}
//Need to send ACK when the response is CON
return;
}
- OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
}
//copy request payload
if (requestInfo->info.payload)
{
- size_t payloadLen = strlen(requestInfo->info.payload);
- serverRequest.reqTotalSize = payloadLen + 1;
- OICStrcpy(serverRequest.reqJSONPayload, sizeof(serverRequest.reqJSONPayload),
- requestInfo->info.payload);
+ serverRequest.reqTotalSize = requestInfo->info.payloadSize;
+ memcpy (&(serverRequest.payload), requestInfo->info.payload,
+ requestInfo->info.payloadSize);
}
else
{
- serverRequest.reqTotalSize = 1;
- serverRequest.reqJSONPayload[0] = '\0';
+ serverRequest.reqTotalSize = 0;
}
switch (requestInfo->method)
protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
protocolRequest->observationOption, protocolRequest->qos,
protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
- protocolRequest->reqJSONPayload, protocolRequest->requestToken,
+ protocolRequest->payload, protocolRequest->requestToken,
protocolRequest->tokenLength,
protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
&protocolRequest->devAddr);
// Free memory dynamically allocated for resources
deleteAllResources();
DeleteDeviceInfo();
+ DeletePlatformInfo();
CATerminate();
// Remove all observers
DeleteObserverList();
// TODO after BeachHead delivery: consolidate into single SRMDeInit()
SRMDeInitPolicyEngine();
+
stackState = OC_STACK_UNINITIALIZED;
return OC_STACK_OK;
}
end = (colon && colon < slash) ? colon : slash;
}
size_t len = end - start;
- if (len > MAX_ADDR_STR_SIZE)
+ if (len >= sizeof(da->addr))
{
return OC_STACK_INVALID_URI;
}
}
}
- da = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
+ da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
if (!da)
{
return OC_STACK_NO_MEMORY;
}
- strncpy(da->addr, start, len);
+ OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
da->port = port;
da->adapter = adapter;
da->flags = flags;
OCMethod method,
const char *requestUri,
const OCDevAddr *destination,
- const char *request,
+ OCPayload* payload,
OCConnectivityType connectivityType,
OCQualityOfService qos,
OCCallbackData *cbData,
goto exit;
}
- if ((request) && (strlen(request) > MAX_REQUEST_LENGTH))
- {
- result = OC_STACK_INVALID_PARAM;
- goto exit;
- }
-
/*
* Support original behavior with address on resourceUri argument.
*/
flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
+
if (result != OC_STACK_OK)
{
OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
requestInfo.info.token = token;
requestInfo.info.tokenLength = tokenLength;
requestInfo.info.resourceUri = resourceUri;
- requestInfo.info.payload = (char *)request;
+
if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
{
result = CreateObserveHeaderOption (&(requestInfo.info.options),
// create remote endpoint
result = OCCreateEndpoint(devAddr, &endpoint);
+ if(payload)
+ {
+ if((result =
+ OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
+ != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
+ goto exit;
+ }
+ }
+ else
+ {
+ requestInfo.info.payload = NULL;
+ requestInfo.info.payloadSize = 0;
+ }
+
+
+
if (result != OC_STACK_OK)
{
OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
{
goto exit;
}
- OICFree(resourceUri);
+
+ // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
+ // Presence notification will form a canonical uri to
+ // look for callbacks into the application.
resourceUri = presenceUri;
}
#endif
}
OICFree(resHandle);
}
+
+ // This is the owner of the payload object, so we free it
+ OCPayloadDestroy(payload);
OICFree(devAddr);
OICFree(resourceUri);
OICFree(resourceType);
return OC_STACK_ERROR;
}
requestData.numOptions = numOptions + 1;
+ requestData.resourceUri = OICStrdup (clientCB->requestUri);
+
requestInfo.method = CA_GET;
requestInfo.info = requestData;
{
OICFree(requestData.options);
}
+ if (requestData.resourceUri)
+ {
+ OICFree (requestData.resourceUri);
+ }
return ret;
}
clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
clientResponse.devAddr = *cbNode->devAddr;
FixUpClientResponse(&clientResponse);
- clientResponse.resJSONPayload = NULL;
+ clientResponse.payload = NULL;
// Increment the TTLLevel (going to a next state), so we don't keep
// sending presence notification to client.
requestData.type = CA_MSG_NONCONFIRM;
requestData.token = cbNode->token;
requestData.tokenLength = cbNode->tokenLength;
+ requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
requestInfo.method = CA_GET;
requestInfo.info = requestData;
return OC_STACK_ERROR;
}
- AddObserver(OC_PRESENCE_URI, NULL, 0, caToken, tokenLength,
+ AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
(OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
CADestroyToken(caToken);
}
if(presenceResource.handle)
{
((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
- }
// make resource inactive
result = OCChangeResourceProperty(
&(((OCResource *) presenceResource.handle)->resourceProperties),
OC_ACTIVE, 0);
+ }
if(result != OC_STACK_OK)
{
return OC_STACK_INVALID_URI;
}
// Is it presented during resource discovery?
- if (!handle || !resourceTypeName)
+ if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
{
OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
return OC_STACK_INVALID_PARAM;
OCNotifyListOfObservers (OCResourceHandle handle,
OCObservationId *obsIdList,
uint8_t numberOfIds,
- const char *notificationJSONPayload,
+ const OCRepPayload *payload,
OCQualityOfService qos)
{
OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
- VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
+ VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
// Verify that the resource exists
resPtr = findResource ((OCResource *) handle);
incrementSequenceNumber(resPtr);
}
return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
- notificationJSONPayload, maxAge, qos));
+ payload, maxAge, qos));
}
OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
- // TODO: Placeholder for creating a response entry when implementing
- // block transfer feature
-
- // If a response payload is present, check if block transfer is required
- if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
- (const char *)ehResponse->payload, ehResponse->payloadSize))
+ // Normal response
+ // Get pointer to request info
+ serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
+ if(serverRequest)
{
- OC_LOG(INFO, TAG, PCF("Block transfer required"));
-
- // Persistent response buffer is needed for block transfer
- if (!ehResponse->persistentBufferFlag)
- {
- OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
- return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
- }
- // TODO: Placeholder for block transfer handling
- // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
- // when implementing the block transfer feature
- }
- else
- {
- // Normal response
- // Get pointer to request info
- serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
- if(serverRequest)
- {
- result = serverRequest->ehResponseHandler(ehResponse);
- }
+ result = serverRequest->ehResponseHandler(ehResponse);
}
+
return result;
}
result = OCCreateResource(&presenceResource.handle,
OC_RSRVD_RESOURCE_TYPE_PRESENCE,
"core.r",
- OC_PRESENCE_URI,
+ OC_RSRVD_PRESENCE_URI,
NULL,
NULL,
OC_OBSERVABLE);
return pointer;
}
-bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size)
-{
- bool result = false;
-
- // Determine if we are checking a request or a response
- if (request)
- {
- // If size is greater than 0, use it for the request size value, otherwise
- // assume request is null terminated and use strlen for size value
- if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
- {
- result = true;
- }
- }
- else if (response)
- {
- // If size is greater than 0, use it for the response size value, otherwise
- // assume response is null terminated and use strlen for size value
- if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
- {
- result = true;
- }
- }
- return result;
-}
-
/*
* This function splits the uri using the '?' delimiter.
* "uriWithoutQuery" is the block of characters between the beginning
#define ACTIONSET "ActionSet"
#define DELETE_ACTIONSET "DelActionSet"
-#define OIC_ACTION_PREFIX "{\"oc\":[{\"rep\":{"
+#define OIC_ACTION_PREFIX "{\"oic\":[{\"rep\":{"
#define VARIFY_POINTER_NULL(pointer, result, toExit) \
if(pointer == NULL) \
{\
{
int idx;
- unsigned char *responseJson;
- responseJson = (unsigned char *) OICMalloc(
- (unsigned int) (strlen((char *) clientResponse->resJSONPayload)
- + 1));
+ unsigned char *responseJson = NULL;
+ // TODO: Figure out what this does, change implementation
+ //responseJson = (unsigned char *) OICMalloc(
+ // (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));
- idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN;
+ // TODO: Taken out
+ //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 = (char*)responseJson;
- response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
+ // TODO: Removing payload size, waht goes here?
+ // response.payload = (char*)responseJson;
+ //response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
response.persistentBufferFlag = 0;
response.requestHandle = (OCRequestHandle) info->ehRequest;
response.resourceHandle = (OCResourceHandle) info->collResource;
cbdata.cd = NULL;
cbdata.context = (void*)DEFAULT_CONTEXT_VALUE;
- return OCDoResource(handle, OC_REST_PUT, targetUri,
- NULL, (char *) action, CT_ADAPTER_IP, OC_NA_QOS, &cbdata, NULL, 0);
+ // TODO: disabled since this is no longer compatible
+ return OC_STACK_NOTIMPL;
+ //return OCDoResource(handle, OC_REST_PUT, targetUri,
+ // NULL, (char *) action, CT_ADAPTER_IP, OC_NA_QOS, &cbdata, NULL, 0);
}
OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
actionDescPtr);
if (result != OC_STACK_OK)
{
+ OICFree(info);
return result;
}
char *jsonResponse;
- stackRet = ExtractKeyValueFromRequest((char *) ehRequest->reqJSONPayload,
- &doWhat, &details);
+ stackRet = OC_STACK_NOTIMPL;
+ // TODO: Fix?
+ //stackRet = ExtractKeyValueFromRequest((char *) ehRequest->reqJSONPayload,
+ // &doWhat, &details);
if(stackRet != OC_STACK_OK)
{
response.ehResult = OC_EH_OK;
else
response.ehResult = OC_EH_ERROR;
- response.payload = (char*)buffer;
- response.payloadSize = bufferLength + 1;
+ // TODO: Fix
+ //response.payload = (char*)buffer;
+ //response.payloadSize = bufferLength + 1;
response.persistentBufferFlag = 0;
response.requestHandle =
(OCRequestHandle) ehRequest->requestHandle;
response.ehResult = OC_EH_OK;
else
response.ehResult = OC_EH_ERROR;
- response.payload = (char *)buffer;
- response.payloadSize = bufferLength + 1;
+ // TODO: Implement
+ //response.payload = (char *)buffer;
+ //response.payloadSize = bufferLength + 1;
response.persistentBufferFlag = 0;
response.requestHandle =
(OCRequestHandle) ehRequest->requestHandle;
/* Start a discovery query*/
char szQueryUri[64] = { 0 };
- strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
+ strcpy(szQueryUri, OC_RSRVD_WELL_KNOWN_URI);
cbData.cb = asyncDoResourcesCallback;
cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
cbData.cd = NULL;
/* Start a discovery query*/
char szQueryUri[64] = { 0 };
- strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
+ strcpy(szQueryUri, OC_RSRVD_WELL_KNOWN_URI);
cbData.cb = asyncDoResourcesCallback;
cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
cbData.cd = NULL;
EXPECT_EQ(OC_STACK_OK, OCStop());
}
+TEST(StackResource, CreateResourceSuccessWithResourcePolicyPropNone)
+{
+ itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+ OC_LOG(INFO, TAG, "Starting CreateResourceSuccessWithResourcePolicyPropNone test");
+ InitStack(OC_SERVER);
+
+ OCResourceHandle handle;
+ // the resource is non-discoverable & non-observable by the client.
+ EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
+ "core.led",
+ "core.rw",
+ "/a/led",
+ 0,
+ NULL,
+ OC_RES_PROP_NONE));// the resource is non-discoverable &
+ // non-observable by the client.
+ const char* url = OCGetResourceUri(handle);
+ EXPECT_STREQ("/a/led", url);
+
+ EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackResource, CreateResourceWithClientStackMode)
+{
+ itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+ OC_LOG(INFO, TAG, "Starting CreateResourceSuccess test");
+ InitStack(OC_CLIENT);
+
+ OCResourceHandle handle;
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, OCCreateResource(&handle,
+ "core.led",
+ "core.rw",
+ "/a/led",
+ 0,
+ NULL,
+ OC_DISCOVERABLE|OC_OBSERVABLE));
+
+ EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
TEST(StackResource, CreateResourceFailDuplicateUri)
{
itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
NULL,
OC_DISCOVERABLE|OC_OBSERVABLE));
+ OCResourceHandle handle2;
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, OCCreateResource(&handle2,
+ "",
+ "core.rw",
+ "/a/led",
+ 0,
+ NULL,
+ OC_DISCOVERABLE|OC_OBSERVABLE));
+
EXPECT_EQ(OC_STACK_OK, OCStop());
}
uint8_t numExpectedResources = 0;
EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numExpectedResources));
-
+
OCResourceHandle handle0;
EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
"core.led",
EXPECT_EQ(OC_STACK_OK, OCStop());
}
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
- void parsePresencePayload(char* payload, uint32_t* seqNum,
- uint32_t* maxAge, OCPresenceTrigger* presenceTrigger, char** resType);
-#ifdef __cplusplus
-}
-#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;
- OCPresenceTrigger presenceTrigger = OC_PRESENCE_TRIGGER_CHANGE;
- char * resType = NULL;
-
- //Good Scenario
- strncpy(payload, "{\"oic\":[{\"ttl\":99,\"non\":100,\"trg\":"
- "\"delete\",\"rt\":\"presence\"}]}", sizeof(payload));
- parsePresencePayload(payload, &seqNum, &maxAge,
- &presenceTrigger, &resType);
- EXPECT_TRUE(100 == seqNum);
- EXPECT_TRUE(99 == maxAge);
- EXPECT_TRUE(OC_PRESENCE_TRIGGER_DELETE == presenceTrigger);
- EXPECT_TRUE(NULL != resType);
- EXPECT_STREQ("presence", resType);
- OICFree(resType);
-
- presenceTrigger = OC_PRESENCE_TRIGGER_CHANGE;
-
- //Bad Scenario -- should not result in Seg Fault
- parsePresencePayload(payload, NULL, &maxAge, &presenceTrigger, &resType);
-
- //Bad Scenario
- seqNum = 0; maxAge = 0; resType = NULL;
- strncpy(payload, "{abracadabra}", sizeof(payload));
- parsePresencePayload(payload, &seqNum, &maxAge, &presenceTrigger, &resType);
- EXPECT_TRUE(0 == seqNum);
- EXPECT_TRUE(0 == maxAge);
- EXPECT_TRUE(OC_PRESENCE_TRIGGER_CHANGE == presenceTrigger);
- EXPECT_TRUE(NULL == resType);
- EXPECT_EQ(NULL, resType);
- OICFree(resType);
-
- //Bad Scenario
- seqNum = 0; maxAge = 0; resType = NULL;
- strncpy(payload, "{\"oic\":[100]}", sizeof(payload));
- parsePresencePayload(payload, &seqNum, &maxAge, &presenceTrigger, &resType);
- EXPECT_TRUE(0 == seqNum);
- EXPECT_TRUE(0 == maxAge);
- EXPECT_TRUE(OC_PRESENCE_TRIGGER_CHANGE == presenceTrigger);
- EXPECT_TRUE(NULL == resType);
- EXPECT_EQ(NULL, resType);
- OICFree(resType);
-
- //Bad Scenario
- seqNum = 0; maxAge = 0; resType = NULL;
- strncpy(payload, "{\"oic\":[]}", sizeof(payload));
- parsePresencePayload(payload, &seqNum, &maxAge, &presenceTrigger, &resType);
- EXPECT_TRUE(0 == seqNum);
- EXPECT_TRUE(0 == maxAge);
- EXPECT_TRUE(OC_PRESENCE_TRIGGER_CHANGE == presenceTrigger);
- EXPECT_TRUE(NULL == resType);
- EXPECT_EQ(NULL, resType);
- OICFree(resType);
-
- //Bad Scenario
- strncpy(payload, "{:]}", sizeof(payload));
- parsePresencePayload(payload, &seqNum, &maxAge, &presenceTrigger, &resType);
- EXPECT_TRUE(0 == seqNum);
- EXPECT_TRUE(0 == maxAge);
- EXPECT_TRUE(OC_PRESENCE_TRIGGER_CHANGE == presenceTrigger);
- EXPECT_TRUE(NULL == resType);
- EXPECT_EQ(NULL, resType);
- OICFree(resType);
-
- //Bad Scenario
- strncpy(payload, "{:[presence}", sizeof(payload));
- parsePresencePayload(payload, &seqNum, &maxAge, &presenceTrigger, &resType);
- EXPECT_TRUE(0 == seqNum);
- EXPECT_TRUE(0 == maxAge);
- EXPECT_TRUE(OC_PRESENCE_TRIGGER_CHANGE == presenceTrigger);
- EXPECT_TRUE(NULL == resType);
- EXPECT_EQ(NULL, resType);
- OICFree(resType);
-}
-
TEST(PODTests, OCHeaderOption)
{
EXPECT_TRUE(std::is_pod<OCHeaderOption>::value);
# and error messages should be written. If left blank the output is written
# to stderr.
-WARN_LOGFILE =
+WARN_LOGFILE = ./doxygen.log
#---------------------------------------------------------------------------
# configuration options related to the input files
../include/OCResourceRequest.h \
../include/OCResourceResponse.h \
../include/OCResource.h \
- ../resource/csdk/stack/include/octypes.h \
- ../resource/csdk/stack/include/ocstackconfig.h \
+ ../csdk/stack/include/octypes.h \
+ ../csdk/stack/include/ocstackconfig.h \
guides \
../../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
+ ../../service/notification-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
using namespace OC;
+static void printUsage()
+{
+ std::cout << "Usage devicediscoveryclient <0|1>" << std::endl;
+ std::cout << "connectivityType: Default IP" << std::endl;
+ std::cout << "connectivityType 0: IPv4" << std::endl;
+ std::cout << "connectivityType 1: IPv6 (Currently not supported !)" << std::endl;
+}
//Callback after device information is received
void receivedPlatformInfo(const OCRepresentation& rep)
{
std::string platformDiscoveryURI = "/oic/p";
std::string deviceDiscoveryURI = "/oic/d";
+ //Default Connectivity type
OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
if(optionSelected == 0)
{
- connectivityType = CT_ADAPTER_IP;
+ std::cout << "Using IPv4."<< std::endl;
+ connectivityType = CT_IP_USE_V4;
+ }
+ else if(optionSelected == 1)
+ {
+ std::cout << "IPv6 is currently not supported."<< std::endl;
+ printUsage();
+ return -1;
+ //TODO: printUsage to be removed when IPv6 is available.
+ //connectivityType = CT_ADAPTER_IP;
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IP"
- << std::endl;
+ std::cout << "Invalid connectivity type selected." << std::endl;
+ printUsage();
+ return -1;
}
}
else
}
else
{
- std::cout << "Usage devicediscoveryclient 0" << std::endl;
- std::cout << "connectivityType: Default IP" << std::endl;
- std::cout << "connectivityType 0: IP" << std::endl;
+ printUsage();
}
// Create PlatformConfig object
PlatformConfig cfg {
const uint16_t API_VERSION = 2048;
const uint16_t TOKEN = 3000;
+static void printUsage()
+{
+ std::cout << "Usage: fridgeclient <0|1>" <<std::endl;
+ std::cout << "connectivityType: Default IP" << std::endl;
+ std::cout << "connectivityType 0: IPv4" << std::endl;
+ std::cout << "connectivityType 1: IPv6 (Currently Not Supported)" << std::endl;
+}
class ClientFridge
{
public:
m_callsMade(0),m_connectivityType(ct)
{
std::ostringstream requestURI;
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=intel.fridge";
+ requestURI << OC_RSRVD_WELL_KNOWN_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(
// however be a better fit to wrap each call in an object so a fuller context (and additional
// requests) can be easily made inside of a simple context
void getResponse(const std::string& resourceName, const HeaderOptions& headerOptions,
- const OCRepresentation rep, const int eCode, OCResource::Ptr resource, int getId)
+ const OCRepresentation& rep, const int eCode, OCResource::Ptr resource, int getId)
{
std::cout << "Got a response from get from the " << resourceName << std::endl;
std::cout << "Get ID is "<<getId<<" and resource URI is " << resource->uri() << std::endl;
{
if(optionSelected == 0)
{
- connectivityType = CT_ADAPTER_IP;
+ std::cout << "Using IPv4."<< std::endl;
+ connectivityType = CT_IP_USE_V4;
+ }
+ else if(optionSelected == 1)
+ {
+ std::cout << "IPv6 is currently not supported."<< std::endl;
+ printUsage();
+ return -1;
+ //TODO: printUsage to be removed when IPv6 is available.
+ //connectivityType = CT_IP_USE_V6;
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IP"
- << std::endl;
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
+ printUsage();
}
}
else
}
else
{
- std::cout << "Usage: fridgeclient 0\n";
- std::cout << "connectivityType: Default IP" << std::endl;
- std::cout << "connectivityType 0: IP" << std::endl;
+ printUsage();
+ std::cout << "Default input argument. Using IP as connectivity type" << std::endl;
}
PlatformConfig cfg
return m_rep;
}
- void put(OCRepresentation rep)
+ void put(const OCRepresentation& rep)
{
rep.getValue("on", m_isOn);
}
return m_rep;
}
- void put(OCRepresentation rep)
+ void put(const OCRepresentation& rep)
{
rep.getValue("open", m_isOpen);
// Note, we won't let the user change the door side!
std::shared_ptr<OCResource> curResource;
std::mutex curResourceLock;
+static void printUsage()
+{
+ std::cout<<"Usage: garageclient <0|1> \n";
+ std::cout<<"ConnectivityType: Default IP\n";
+ std::cout<<"ConnectivityType 0: IPv4 \n";
+ std::cout<<"ConnectivityType 1: IPv6 \n";
+}
+
class Garage
{
public:
std::ostringstream requestURI;
- OCConnectivityType connectivityType = CT_DEFAULT;
+ OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
{
if(optionSelected == 0)
{
- connectivityType = CT_ADAPTER_IP;
+ std::cout << "Using IPv4."<< std::endl;
+ connectivityType = CT_IP_USE_V4;
+ }
+ else if(optionSelected == 1)
+ {
+ std::cout << "IPv6 is currently not supported."<< std::endl;
+ printUsage();
+ return -1;
+ //TODO: printUsage to be removed when IPv6 is available.
+ //connectivityType = CT_IP_USE_V6;
}
else
{
}
else
{
- std::cout<<"Usage: garageclient 0\n";
- std::cout<<"ConnectivityType: Default IP\n";
- std::cout<<"ConnectivityType 0: IP\n";
+ printUsage();
+ std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
}
// Create PlatformConfig object
try
{
// Find all resources
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.garage";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.garage";
OCPlatform::findResource("", requestURI.str(),
connectivityType, &foundResource);
int main(int argc, char* argv[])
{
ostringstream requestURI;
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=a.collection";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=a.collection";
PlatformConfig config
{ OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos };
OCResourceHandle resourceHandle;
std::vector< OCResourceHandle > resourceHandleVector;
+static void printUsage()
+{
+ std::cout<<"Usage: groupclient <0|1>\n";
+ std::cout<<"ConnectivityType: Default \n";
+ std::cout<<"ConnectivityType 0: IPv4\n";
+ std::cout<<"ConnectivityType 1: IPv6\n";
+}
void foundResource(std::shared_ptr< OCResource > resource)
{
{
ostringstream requestURI;
- OCConnectivityType connectivityType = CT_DEFAULT;
+ OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
{
if(optionSelected == 0)
{
- connectivityType = CT_ADAPTER_IP;
+ std::cout << "Using IPv4."<< std::endl;
+ connectivityType = CT_IP_USE_V4;
+ }
+ else if(optionSelected == 1)
+ {
+ std::cout << "IPv6 is currently not supported."<< std::endl;
+ printUsage();
+ return -1;
+ //TODO: printUsage to be removed when IPv6 is available.
+ //connectivityType = CT_IP_USE_V6;
}
else
{
}
else
{
- std::cout<<"Usage: groupclient 0\n";
- std::cout<<"ConnectivityType: Default \n";
- std::cout<<"ConnectivityType 0: IP\n";
+ printUsage();
+
}
PlatformConfig config
cout << "registerResource is called." << endl;
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
OCPlatform::findResource("", requestURI.str(),
connectivityType, &foundResource);
<< 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;
+ std::cout << "-c 1 : Send message with IPv6 (Currently Not Supported)" << std::endl;
}
// Callback to presence
{
if(optionSelected == 0)
{
- connectivityType = CT_ADAPTER_IP;
+ std::cout << "Using IPv4."<< std::endl;
+ connectivityType = CT_IP_USE_V4;
+ }
+ else if(optionSelected == 1)
+ {
+ std::cout << "IPv6 is currently not supported."<< std::endl;
+ printUsage();
+ return -1;
+ //TODO: printUsage to be removed when IPv6 is available.
+ //connectivityType = CT_IP_USE_V6;
}
else
{
else
{
// Find all resources
- requestURI << OC_MULTICAST_DISCOVERY_URI;
+ requestURI << OC_RSRVD_WELL_KNOWN_URI;
result = OCPlatform::findResource("", requestURI.str(),
CT_DEFAULT, &foundResource);
return ++oc;
}
+static void printUsage()
+{
+ std::cout << "Usage roomclient <0|1>" << std::endl;
+ std::cout<<"connectivityType: Default" << std::endl;
+ std::cout << "connectivityType 0: IPv4" << std::endl;
+ std::cout << "connectivityType 0: IPv46 (Currently Not Supported)" << std::endl;
+}
// Forward declaration
void putRoomRepresentation(std::shared_ptr<OCResource> resource);
void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
std::ostringstream requestURI;
- OCConnectivityType connectivityType = CT_DEFAULT;
+ OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
try
{
if(optionSelected == 0)
{
- connectivityType = CT_ADAPTER_IP;
+ std::cout << "Using IPv4."<< std::endl;
+ connectivityType = CT_IP_USE_V4;
+ }
+ else if(optionSelected == 1)
+ {
+ std::cout << "IPv6 is currently not supported."<< std::endl;
+ printUsage();
+ return -1;
+ //TODO: printUsage to be removed when IPv6 is available.
+ //connectivityType = CT_IP_USE_V6;
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
+ std::cout << "Invalid connectivity type selected. Using default IP"<< std::endl;
}
}
else
}
else
{
- std::cout << "Usage roomclient 0" << std::endl;
- std::cout<<"connectivityType: Default" << std::endl;
- std::cout << "connectivityType 0: IP" << std::endl;
+ std::cout << "Default input argument. Using IP as Default connectivity type" << std::endl;
+ printUsage();
}
// Create PlatformConfig object
try
{
// Find all resources
- requestURI << OC_MULTICAST_DISCOVERY_URI;
+ requestURI << OC_RSRVD_WELL_KNOWN_URI;
OCPlatform::findResource("", requestURI.str(), connectivityType, &foundResource);
std::cout<< "Finding Resource... " <<std::endl;
// 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.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI;// << "?rt=core.light";
OCPlatform::findResource("", requestURI.str(),
CT_DEFAULT, &foundResource);
std::cout << " ObserveType : 1 - Observe" << std::endl;
std::cout << " ObserveType : 2 - ObserveAll" << std::endl;
std::cout << " ConnectivityType: Default IP" << std::endl;
- std::cout << " ConnectivityType : 0 - IP"<< std::endl;
+ std::cout << " ConnectivityType : 0 - IPv4"<< std::endl;
+ std::cout << " ConnectivityType : 0 - IPv6 (Current Not Supported )"<< std::endl;
}
int main(int argc, char* argv[]) {
std::ostringstream requestURI;
- OCConnectivityType connectivityType = CT_DEFAULT;
+ OCConnectivityType connectivityType = CT_ADAPTER_IP;
try
{
if (argc == 1)
{
if(optionSelected == 0)
{
- connectivityType = CT_ADAPTER_IP;
+ std::cout << "Using IPv4."<< std::endl;
+ connectivityType = CT_IP_USE_V4;
+ }
+ else if(optionSelected == 1)
+ {
+ std::cout << "IPv6 is currently not supported."<< std::endl;
+ PrintUsage();
+ return -1;
+ //TODO: printUsage to be removed when IPv6 is available.
+ //connectivityType = CT_IP_USE_V6;
}
else
{
catch(std::exception& e)
{
std::cout << "Invalid input argument." << std::endl;
+ PrintUsage();
+ return -1;
}
try
{
// Find all resources
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
OCPlatform::findResource("", requestURI.str(),
connectivityType, &foundResource, OC::QualityOfService::LowQos);
#include "OCApi.h"
using namespace OC;
+static void printUsage()
+{
+ std::cout<< " Usage simpleclientserver <0|1>" << std::endl;
+ std::cout<< " ConnectivityType: Default IP" << std::endl;
+ std::cout << " ConnectivityType : 0 - IPv4" << std::endl;
+ std::cout << " ConnectivityType : 1 - IPv6 (Currently Not Supported)" << std::endl;
+}
class ClientWorker
{
void start()
{
std::ostringstream requestURI;
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.foo";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.foo";
std::cout<<"Starting Client find:"<<std::endl;
FindCallback f (std::bind(&ClientWorker::foundResource, this, std::placeholders::_1));
{
if(optionSelected == 0)
{
- connectivityType = CT_ADAPTER_IP;
+ std::cout << "Using IPv4."<< std::endl;
+ connectivityType = CT_IP_USE_V4;
+ }
+ else if(optionSelected == 1)
+ {
+ std::cout << "IPv6 is currently not supported."<< std::endl;
+ printUsage();
+ return -1;
+ //TODO: printUsage to be removed when IPv6 is available.
+ //connectivityType = CT_IP_USE_V6;
}
else
{
}
else
{
- std::cout<< "Usage simpleclientserver 0>" << std::endl;
- std::cout<< " ConnectivityType: Default IP" << std::endl;
- std::cout << " ConnectivityType : 0 - IP" << std::endl;
+ printUsage();
}
PlatformConfig cfg {
int main(int argc, char* argv[])
{
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.foo";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.foo";
PlatformConfig cfg {
OC::ServiceType::InProc,
#include <iostream>
#include <OCApi.h>
-#include <ocstack.h>
#include <IClientWrapper.h>
#include <InitializeException.h>
#include <ResourceInitException.h>
private:
void listeningFunc();
std::string assembleSetResourceUri(std::string uri, const QueryParamsMap& queryParams);
- std::string assembleSetResourcePayload(const OCRepresentation& attributes);
+ OCPayload* assembleSetResourcePayload(const OCRepresentation& attributes);
OCHeaderOption* assembleHeaderOptions(OCHeaderOption options[],
const HeaderOptions& headerOptions);
std::thread m_listeningThread;
#include <thread>
#include <mutex>
-#include <ocstack.h>
#include <IServerWrapper.h>
#define _INITIALIZE_EXCEPTION_H_
#include <stdexcept>
-#include <ocstack.h>
#include "StringConstants.h"
namespace OC
* ModeType : indicate whether we want to do server, client or both
* ServerConnectivity : default flags for server
* ClientConnectivity : default flags for client
- * QoS : Quality of Service : CONFIRMABLE or NON CONFIRMABLE.
+ * QoS : indicate Quality of Service : LowQos, MidQos,HighQos and NaQos(No quality Defined).
* ps : persistant storage Handler structure (open/read/write/close/unlink)
*/
struct PlatformConfig
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.grp";
+ const std::string GROUP_INTERFACE = "oic.mi.grp";
typedef std::function<void(std::shared_ptr<OCResource>)> FindCallback;
#include <stdexcept>
#include <string>
-#include <ocstack.h>
+#include <octypes.h>
namespace OC {
#include <OCException.h>
-namespace cereal
-{
- class access;
-}
-
namespace OC
{
DefaultChild
};
- // The consumer requires resource info to be printed in 2 different ways, both with the "oc":[]
- // and without. This enum is used to differentiate between the two situations. When the
- // serialize is called with Include OC, we encode OC, otherwise we skip it and return just the
- // contents of the array.
- enum class OCInfoFormat
- {
- IncludeOC,
- ExcludeOC
- };
-
class MessageContainer
{
public:
- void setJSONRepresentation(const std::string& payload);
+ void setPayload(const OCPayload* rep);
+
+ void setPayload(const OCDevicePayload* rep);
- void setJSONRepresentation(const char* payload);
+ void setPayload(const OCPlatformPayload* rep);
- std::string getJSONRepresentation(OCInfoFormat f) const;
+ void setPayload(const OCRepPayload* rep);
+
+ OCRepPayload* getPayload() const;
const std::vector<OCRepresentation>& representations() const;
virtual ~OCRepresentation(){}
- std::string getJSONRepresentation() const;
+ OCRepPayload* getPayload() const;
void addChild(const OCRepresentation&);
void setResourceTypes(const std::vector<std::string>& resourceTypes);
+ void addResourceType(const std::string& str);
+
const std::vector<std::string>& getResourceInterfaces() const;
void setResourceInterfaces(const std::vector<std::string>& resourceInterfaces);
+ void addResourceInterface(const std::string& str);
+
bool emptyData() const;
int numberOfAttributes() const;
const AttributeItem operator[](const std::string& key) const;
private:
friend class OCResourceResponse;
- friend class cereal::access;
-
+ friend class MessageContainer;
+
+ template<typename T>
+ void payload_array_helper(const OCRepPayloadValue* pl, size_t depth);
+ template<typename T>
+ T payload_array_helper_copy(size_t index, const OCRepPayloadValue* pl);
+ void setPayload(const OCRepPayload* payload);
+ void setPayloadArray(const OCRepPayloadValue* pl);
+ void getPayloadArray(OCRepPayload* payload,
+ const OCRepresentation::AttributeItem& item) const;
// the root node has a slightly different JSON version
// based on the interface type configured in ResourceResponse.
// This allows ResourceResponse to set it, so that the save function
m_interfaces(interfaces)
{}*/
private:
- friend class cereal::access;
- template <class Archive>
- void save(Archive& ar) const;
-
- template<class Archive>
- void load(Archive& ar);
-
std::vector<std::string>& m_types;
std::vector<std::string>& m_interfaces;
};
- template<class Archive, class Val>
- static void optional_load(Archive& ar, Val&& v);
-
- template<class Archive>
- void save(Archive& ar) const;
-
- template<class Archive>
- void load(Archive& ar);
-
private:
std::string m_uri;
std::vector<OCRepresentation> m_children;
bool operator>=(const OCResource &other) const;
private:
+ void setHost(const std::string& host);
std::weak_ptr<IClientWrapper> m_clientWrapper;
std::string m_uri;
OCResourceIdentifier m_resourceId;
OCDevAddr m_devAddr;
+ bool m_useHostString;
bool m_isObservable;
bool m_isCollection;
std::vector<std::string> m_resourceTypes;
m_requestType = requestType;
}
- void setPayload(const std::string& requestPayload);
+ void setPayload(OCPayload* requestPayload);
void setQueryParams(QueryParamsMap& queryParams)
{
private:
friend class InProcServerWrapper;
- std::string getPayload() const
+ OCRepPayload* getPayload() const
{
MessageContainer inf;
OCRepresentation first(m_representation);
}
- return inf.getJSONRepresentation(OCInfoFormat::ExcludeOC);
+ return inf.getPayload();
}
public:
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include <cereal/cereal.hpp>
-#include <cereal/types/memory.hpp>
-#include <cereal/types/vector.hpp>
-#include <cereal/archives/json.hpp>
-
#include <StringConstants.h>
+#include "ocpayload.h"
+#include "ocrandom.h"
namespace OC
{
class ListenOCContainer
{
private:
+ static std::vector<std::string> StringLLToVector(OCStringLL* ll)
+ {
+ std::vector<std::string> strs;
+ while(ll)
+ {
+ strs.push_back(ll->value);
+ ll = ll->next;
+ }
+ return strs;
+ }
+
+ public:
+ ListenOCContainer(std::weak_ptr<IClientWrapper> cw,
+ OCDevAddr& devAddr, OCDiscoveryPayload* payload)
+ : m_clientWrapper(cw), m_devAddr(devAddr)
+ {
+ OCResourcePayload* res = payload->resources;
+
+ while(res)
+ {
+ char uuidString[UUID_STRING_SIZE];
+ if(OCConvertUuidToString(res->sid, uuidString) != RAND_UUID_OK)
+ {
+ uuidString[0]= '\0';
+ }
+
+ if (res->secure)
+ {
+ m_devAddr.flags =
+ (OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags);
+ }
+
+ if (res->port != 0)
+ {
+ m_devAddr.port = res->port;
+ }
+
+ m_resources.push_back(std::shared_ptr<OC::OCResource>(
+ new OC::OCResource(m_clientWrapper, m_devAddr,
+ std::string(res->uri),
+ std::string(uuidString),
+ (res->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
+ StringLLToVector(res->types),
+ StringLLToVector(res->interfaces)
+ )));
+ res = res->next;
+ }
+
+ }
+
+ const std::vector<std::shared_ptr<OCResource>>& Resources() const
+ {
+ return m_resources;
+ }
+ private:
+ std::vector<std::shared_ptr<OC::OCResource>> m_resources;
+ std::weak_ptr<IClientWrapper> m_clientWrapper;
+ OCDevAddr& m_devAddr;
+ };
+ /*
+ class ListenOCContainer
+ {
+ private:
enum class OCSecureType
{
NotSecure,
Secure
};
- class ListenResourceContainer
+ class DiscoveredResources
{
- class ListenResourcePolicyContainer
+ class Resource
{
friend class cereal::access;
- friend class ListenResourceContainer;
- friend class ListenResourcePropertiesContainer;
- template<class Archive>
- void serialize(Archive& ar)
+ class ResourcePolicy
{
- m_secure = false;
- m_port = -1;
+ friend class cereal::access;
+ friend class Resource;
- try
+ template<class Archive>
+ void serialize(Archive& ar)
{
- m_observable = false;
- ar(cereal::make_nvp(OC::Key::BMKEY, m_bm));
- // In case of observable
- if(m_bm & OC_OBSERVABLE)
+ try
+ {
+ m_observable = false;
+ ar(cereal::make_nvp(OC::Key::BMKEY, m_bm));
+
+ if(m_bm & OC_OBSERVABLE)
+ {
+ m_observable = true;
+ }
+ }
+ catch(cereal::Exception&)
{
- m_observable = true;
+ ar.setNextName(nullptr);
}
+
+ try
+ {
+ m_secure = false;
+ int secureTemp;
+ ar(cereal::make_nvp(OC::Key::SECUREKEY, secureTemp));
+ m_secure = secureTemp != 0;
+
+ m_port = -1;
+ ar(cereal::make_nvp(OC::Key::PORTKEY, m_port));
+ }
+ catch(cereal::Exception&)
+ {
+ ar.setNextName(nullptr);
+ }
+ }
+
+ bool m_observable;
+ uint8_t m_bm;
+ bool m_secure;
+ int m_port;
+ };
+
+ template <class Archive>
+ void serialize(Archive& ar)
+ {
+ try
+ {
+ ar(cereal::make_nvp(OC::Key::URIKEY, m_uri));
+ m_loaded = true;
}
catch(cereal::Exception&)
{
ar.setNextName(nullptr);
}
+
try
{
- int secureTemp;
- ar(cereal::make_nvp(OC::Key::SECUREKEY, secureTemp));
- m_secure = secureTemp != 0;
-
- ar(cereal::make_nvp(OC::Key::PORTKEY, m_port));
+ ar(cereal::make_nvp(OC::Key::RESOURCETYPESKEY,m_resourceTypes));
+ m_loaded = true;
}
catch(cereal::Exception&)
{
ar.setNextName(nullptr);
}
- }
-
- bool m_observable;
- uint8_t m_bm;
- bool m_secure;
- int m_port;
- };
-
- class ListenResourcePropertiesContainer
- {
- friend class cereal::access;
- friend class ListenResourceContainer;
-
- template<class Archive>
- void serialize(Archive& ar)
- {
try
{
- ar(cereal::make_nvp(OC::Key::POLICYKEY, m_policy));
-
+ ar(cereal::make_nvp(OC::Key::INTERFACESKEY, m_interfaces));
+ m_loaded = true;
}
catch(cereal::Exception&)
{
- // we swallow this exception, since it means the key
- // doesn't exist, allowing these to be optional
- oclog() << "Invalid POLICYKEY"<<std::flush;
ar.setNextName(nullptr);
}
try
{
- ar(cereal::make_nvp(OC::Key::RESOURCETYPESKEY,m_resourceTypes));
+ ar(cereal::make_nvp(OC::Key::POLICYKEY, m_policy));
+ m_loaded = true;
}
catch(cereal::Exception&)
{
ar.setNextName(nullptr);
}
+
+ // Although not expected, a server id as part of a resource's own
+ // representation is legal. It may be used if needed.
try
{
- ar(cereal::make_nvp(OC::Key::INTERFACESKEY, m_interfaces));
+ ar(cereal::make_nvp(OC::Key::DEVICEIDKEY, m_serverId));
+ m_loaded = true;
}
catch(cereal::Exception&)
{
ar.setNextName(nullptr);
}
}
+ public:
+ Resource(): m_loaded(false)
+ {}
+ bool observable() const
+ {
+ return m_policy.m_observable;
+ }
+
+ OCSecureType secureType() const
+ {
+ return m_policy.m_secure ? OCSecureType::Secure : OCSecureType::NotSecure;
+ }
+
+ int port() const
+ {
+ return m_policy.m_port;
+ }
+
+ std::vector<std::string> resourceTypes() const
+ {
+ return m_resourceTypes;
+ }
+
+ std::vector<std::string> interfaces() const
+ {
+ return m_interfaces;
+ }
+
+ bool loaded() const{
+ return m_loaded;
+ }
+
+ std::string m_uri;
+ std::string m_serverId;
std::vector<std::string> m_resourceTypes;
std::vector<std::string> m_interfaces;
- ListenResourcePolicyContainer m_policy;
+ ResourcePolicy m_policy;
+ bool m_loaded;
};
public:
- ListenResourceContainer() : m_loaded(false)
+ DiscoveredResources()
{}
private:
{
try
{
- ar(cereal::make_nvp(OC::Key::URIKEY, m_uri));
- m_loaded=true;
- }
- catch(cereal::Exception&)
- {
- ar.setNextName(nullptr);
- }
- try
- {
- ar(cereal::make_nvp(OC::Key::SERVERIDKEY, m_serverId));
- m_loaded=true;
- }
- catch(cereal::Exception&)
- {
- ar.setNextName(nullptr);
+ ar(cereal::make_nvp(OC::Key::DEVICEIDKEY, m_serverIdOfThisDevice));
}
+ catch(cereal::Exception&) { ar.setNextName(nullptr); }
+
try
{
- ar(cereal::make_nvp(OC::Key::PROPERTYKEY, m_props));
- m_loaded=true;
+ ar(cereal::make_nvp(OC::Key::LINKS, resources));
}
- catch(cereal::Exception&)
- {
- ar.setNextName(nullptr);
- }
-
- }
-
- std::string m_uri;
- std::string m_serverId;
- bool m_loaded;
- ListenResourcePropertiesContainer m_props;
-
- bool loaded() const
- {
- return m_loaded;
- }
-
- bool observable() const
- {
- return m_props.m_policy.m_observable;
- }
-
- OCSecureType secureType() const
- {
- return m_props.m_policy.m_secure ? OCSecureType::Secure : OCSecureType::NotSecure;
- }
-
- int port() const
- {
- return m_props.m_policy.m_port;
- }
-
- std::vector<std::string> resourceTypes() const
- {
- return m_props.m_resourceTypes;
+ catch(cereal::Exception&) { ar.setNextName(nullptr); }
}
- std::vector<std::string> interfaces() const
- {
- return m_props.m_interfaces;
- }
+ std::string m_serverIdOfThisDevice;
+ std::vector<Resource> resources;
};
private:
template <class Archive>
void serialize(Archive& ar)
{
- std::vector<ListenResourceContainer> resources;
+ std::vector<DiscoveredResources> resources;
ar(resources);
}
public:
ListenOCContainer(std::weak_ptr<IClientWrapper> cw,
const OCDevAddr& devAddr, std::stringstream& json)
: m_clientWrapper(cw), m_devAddr(devAddr)
+
{
LoadFromJson(json);
}
{
cereal::JSONInputArchive archive(json);
- std::vector<ListenResourceContainer> resources;
+ std::vector<DiscoveredResources> resources;
archive(cereal::make_nvp(OC::Key::OCKEY, resources));
m_resources.clear();
- for(const auto& res : resources)
+ for(const auto& resourcesAtDevice : resources)
{
- try
+ std::string serverIDForThisResourceRep = resourcesAtDevice.m_serverIdOfThisDevice;
+
+ for (const auto& resource : resourcesAtDevice.resources)
{
- if(res.loaded())
+ try
{
- if (res.secureType() == OCSecureType::Secure)
- {
- m_devAddr.flags =
- (OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags);
- }
- if (res.port() != -1)
+ if(resource.loaded())
{
- m_devAddr.port = res.port();
+ m_resources.push_back(std::shared_ptr<OCResource>
+ (
+ new OCResource
+ (
+ m_clientWrapper,
+ m_devAddr,
+ resource.m_uri,
+ serverIDForThisResourceRep,
+ resource.observable(),
+ resource.resourceTypes(),
+ resource.interfaces()
+ )
+ ));
}
- m_resources.push_back(std::shared_ptr<OCResource>(
- new OCResource(m_clientWrapper, m_devAddr,
- res.m_uri, res.m_serverId, res.observable(),
- res.resourceTypes(), res.interfaces())));
}
-
- }
- catch(ResourceInitException& e)
- {
- oclog() << "listenCallback(): failed to create resource: " << e.what()
- << std::flush;
+ catch(ResourceInitException& e)
+ {
+ oclog() << "listenCallback(): failed to create resource: " << e.what()
+ << std::flush;
+ }
}
}
}
- std::vector<std::shared_ptr<OC::OCResource>> m_resources;
- std::weak_ptr<IClientWrapper> m_clientWrapper;
- OCDevAddr m_devAddr;
};
+*/
}
+++ /dev/null
-/*! \file OicJsonSerializer.hpp
- \brief JSON input and output archives.
-Note: this has been customized by Intel(R) for usage in the OIC project.
-Nearly the entire file is from Cereal (see copyright notice below) other than specified
-below
-Added:
-#include of AttributeValue Type
-JSONOutputArchive::saveValue() to add JSON null value
-loadAttributeValues to get attribute values out of a map (implemented in OCRepresentation)
-
-*/
-/*
- Copyright (c) 2014, Randolph Voorhies, Shane Grant
- 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.
- * Neither the name of cereal 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 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 RANDOLPH VOORHIES OR SHANE GRANT 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 CEREAL_ARCHIVES_JSON_HPP_
-#define CEREAL_ARCHIVES_JSON_HPP_
-
-#include <AttributeValue.h>
-#include <cereal/cereal.hpp>
-#include <cereal/details/util.hpp>
-namespace cereal
-{
- //! An exception thrown when rapidjson fails an internal assertion
- /*! @ingroup Utility */
- struct RapidJSONException : Exception
- { RapidJSONException( const char * what_ ) : Exception( what_ ) {} };
-}
-
-// Override rapidjson assertions to throw exceptions by default
-#ifndef RAPIDJSON_ASSERT
-#define RAPIDJSON_ASSERT(x) if(!(x)){ \
- throw ::cereal::RapidJSONException("rapidjson internal assertion failure: " #x); }
-#endif // RAPIDJSON_ASSERT
-
-#include <cereal/external/rapidjson/writer.h>
-#include <cereal/external/rapidjson/genericstream.h>
-#include <cereal/external/rapidjson/reader.h>
-#include <cereal/external/rapidjson/document.h>
-#include <cereal/external/base64.hpp>
-
-#include <limits>
-#include <sstream>
-#include <stack>
-#include <vector>
-#include <string>
-
-namespace cereal
-{
- // ######################################################################
- //! An output archive designed to save 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.
-
- JSON benefits greatly from name-value pairs, which if present, will
- name the nodes in the output. If these are not present, each level
- of the output will be given an automatically generated delimited name.
-
- The precision of the output archive controls the number of decimals output
- for floating point numbers and should be sufficiently large (i.e. at least 20)
- if there is a desire to have binary equality between the numbers output and
- those read in. In general you should expect a loss of precision when going
- from floating point to text and back.
-
- JSON archives do not output the size information for any dynamically sized structure
- and instead infer it from the number of children for a node. This means that data
- can be hand edited for dynamic sized structures and will still be readable. This
- is accomplished through the cereal::SizeTag object, which will cause the archive
- to output the data as a JSON array (e.g. marked by [] instead of {}), which indicates
- that the container is variable sized and may be edited.
-
- \ingroup Archives */
- class JSONOutputArchive : public OutputArchive<JSONOutputArchive>
- {
- enum class NodeType { StartObject, InObject, StartArray, InArray };
-
- typedef rapidjson::GenericWriteStream WriteStream;
- typedef rapidjson::Writer<WriteStream> JSONWriter;
-
- public:
- /*! @name Common Functionality
- Common use cases for directly interacting with an JSONOutputArchive */
- //! @{
-
- //! A class containing various advanced options for the JSON archive
- class Options
- {
- public:
- //! Default options
- static Options Default(){ return Options(); }
-
- //! Specify specific options for the JSONOutputArchive
- /*! @param precision The precision used for floating point numbers*/
- explicit Options( int precision = std::numeric_limits<double>::max_digits10) :
- itsPrecision( precision ) { }
-
- private:
- friend class JSONOutputArchive;
- int itsPrecision;
- };
-
- //! Construct, outputting to the provided stream
- /*! @param stream The stream to output to.
- @param options The JSON specific options to use. See the Options struct
- for the values of default parameters */
- JSONOutputArchive(std::ostream & stream, Options const & options = Options::Default() ) :
- OutputArchive<JSONOutputArchive>(this),
- itsWriteStream(stream),
- itsWriter(itsWriteStream, options.itsPrecision),
- itsNextName(nullptr)
- {
- itsNameCounter.push(0);
- itsNodeStack.push(NodeType::StartObject);
- }
-
- //! Destructor, flushes the JSON
- ~JSONOutputArchive()
- {
- itsWriter.EndObject();
- }
-
- //! Saves some binary data, encoded as a base64 string, with an optional name
- /*! This will create a new node, optionally named, and insert a value that consists of
- the data encoded as a base64 string */
- void saveBinaryValue( const void * data, size_t size, const char * name = nullptr )
- {
- setNextName( name );
- writeName();
-
- auto base64string = base64::encode( reinterpret_cast<const unsigned char *>( data ), size );
- saveValue( base64string );
- };
-
- //! @}
- /*! @name Internal Functionality
- Functionality designed for use by those requiring control over the inner mechanisms of
- the JSONOutputArchive */
- //! @{
-
- //! Starts a new node in the JSON output
- /*! The node can optionally be given a name by calling setNextName prior
- to creating the node
-
- Nodes only need to be started for types that are themselves objects or arrays */
- void startNode()
- {
- writeName();
- itsNodeStack.push(NodeType::StartObject);
- itsNameCounter.push(0);
- }
-
- //! Designates the most recently added node as finished
- void finishNode()
- {
- // if we ended up serializing an empty object or array, writeName
- // will never have been called - so start and then immediately end
- // the object/array.
- //
- // We'll also end any object/arrays we happen to be in
- switch(itsNodeStack.top())
- {
- case NodeType::StartArray:
- itsWriter.StartArray();
- case NodeType::InArray:
- itsWriter.EndArray();
- break;
- case NodeType::StartObject:
- itsWriter.StartObject();
- case NodeType::InObject:
- itsWriter.EndObject();
- break;
- }
-
- itsNodeStack.pop();
- itsNameCounter.pop();
- }
-
- //! Sets the name for the next node created with startNode
- void setNextName( const char * name )
- {
- itsNextName = name;
- }
-
- //! Saves a null to the current node, added by Intel
- void saveValue() { itsWriter.Null_(); }
- //! Saves a bool to the current node
- void saveValue(bool b) { itsWriter.Bool_(b); }
- //! Saves an int to the current node
- void saveValue(int i) { itsWriter.Int(i); }
- //! Saves a uint to the current node
- void saveValue(unsigned u) { itsWriter.Uint(u); }
- //! Saves an int64 to the current node
- void saveValue(int64_t i64) { itsWriter.Int64(i64); }
- //! Saves a uint64 to the current node
- void saveValue(uint64_t u64) { itsWriter.Uint64(u64); }
- //! Saves a double to the current node
- void saveValue(double d) { itsWriter.Double(d); }
- //! Saves a string to the current node
- void saveValue(std::string const & s) { itsWriter.String(s.c_str(), static_cast<rapidjson::SizeType>( s.size() )); }
- //! Saves a const char * to the current node
- void saveValue(char const * s) { itsWriter.String(s); }
-
- public:
-#ifdef _MSC_VER
- //! MSVC only long overload to current node
- void saveValue( unsigned long lu ){ saveLong( lu ); };
-#else // _MSC_VER
- //! Serialize a long if it would not be caught otherwise
- template <class T> inline
- typename std::enable_if<std::is_same<T, long>::value &&
- !std::is_same<T, std::int32_t>::value &&
- !std::is_same<T, std::int64_t>::value, void>::type
- saveValue( T t )
- {
- saveLong( t );
- return t;
- }
-
- //! Serialize an unsigned long if it would not be caught otherwise
- template <class T> inline
- typename std::enable_if<std::is_same<T, unsigned long>::value &&
- !std::is_same<T, std::uint32_t>::value &&
- !std::is_same<T, std::uint64_t>::value, void>::type
- saveValue( T t )
- {
- saveLong( t );
- return t;
- }
-#endif // _MSC_VER
-
- //! Save exotic arithmetic as strings to current node
- /*! Handles long long (if distinct from other types), unsigned long (if distinct), and long double */
- template<class T> inline
- typename std::enable_if<std::is_arithmetic<T>::value &&
- !std::is_same<T, long>::value &&
- !std::is_same<T, unsigned long>::value &&
- !std::is_same<T, std::int64_t>::value &&
- !std::is_same<T, std::uint64_t>::value &&
- (sizeof(T) >= sizeof(long double) || sizeof(T) >= sizeof(long long)), void>::type
- saveValue(T const & t)
- {
- std::stringstream ss; ss.precision( std::numeric_limits<long double>::max_digits10 );
- ss << t;
- saveValue( ss.str() );
- return t;
- }
-
- //! Write the name of the upcoming node and prepare object/array state
- /*! Since writeName is called for every value that is output, regardless of
- whether it has a name or not, it is the place where we will do a deferred
- check of our node state and decide whether we are in an array or an object.
-
- The general workflow of saving to the JSON archive is:
-
- 1. (optional) Set the name for the next node to be created, usually done by an NVP
- 2. Start the node
- 3. (if there is data to save) Write the name of the node (this function)
- 4. (if there is data to save) Save the data (with saveValue)
- 5. Finish the node
- */
- void writeName()
- {
- NodeType const & nodeType = itsNodeStack.top();
-
- // Start up either an object or an array, depending on state
- if(nodeType == NodeType::StartArray)
- {
- itsWriter.StartArray();
- itsNodeStack.top() = NodeType::InArray;
- }
- else if(nodeType == NodeType::StartObject)
- {
- itsNodeStack.top() = NodeType::InObject;
- itsWriter.StartObject();
- }
-
- // Array types do not output names
- if(nodeType == NodeType::InArray) return;
-
- if(itsNextName == nullptr)
- {
- std::string name = "value" + std::to_string( itsNameCounter.top()++ ) + "\0";
- saveValue(name);
- }
- else
- {
- saveValue(itsNextName);
- itsNextName = nullptr;
- }
- }
-
- //! Designates that the current node should be output as an array, not an object
- void makeArray()
- {
- itsNodeStack.top() = NodeType::StartArray;
- }
-
- //! @}
-
- private:
- WriteStream itsWriteStream; //!< Rapidjson write stream
- JSONWriter itsWriter; //!< Rapidjson writer
- char const * itsNextName; //!< The next name
- std::stack<uint32_t> itsNameCounter; //!< Counter for creating unique names for unnamed nodes
- std::stack<NodeType> itsNodeStack;
- }; // JSONOutputArchive
-
- // ######################################################################
- //! An input archive designed to load data from JSON
- /*! This archive uses RapidJSON to read in a JSON archive.
-
- Input JSON should have been produced by the JSONOutputArchive. Data can
- only be added to dynamically sized containers (marked by JSON arrays) -
- the input archive will determine their size by looking at the number of child nodes.
- Only JSON originating from a JSONOutputArchive is officially supported, but data
- from other sources may work if properly formatted.
-
- The JSONInputArchive does not require that nodes are loaded in the same
- order they were saved by JSONOutputArchive. Using name value pairs (NVPs),
- it is possible to load in an out of order fashion or otherwise skip/select
- specific nodes to load.
-
- The default behavior of the input archive is to read sequentially starting
- with the first node and exploring its children. When a given NVP does
- not match the read in name for a node, the archive will search for that
- node at the current level and load it if it exists. After loading an out of
- order node, the archive will then proceed back to loading sequentially from
- its new position.
-
- Consider this simple example where loading of some data is skipped:
-
- @code{cpp}
- // imagine the input file has someData(1-9) saved in order at the top level node
- ar( someData1, someData2, someData3 ); // XML loads in the order it sees in the file
- ar( cereal::make_nvp( "hello", someData6 ) ); // NVP given does not
- // match expected NVP name, so we search
- // for the given NVP and load that value
- ar( someData7, someData8, someData9 ); // with no NVP given, loading resumes at its
- // current location, proceeding sequentially
- @endcode
-
- \ingroup Archives */
- class JSONInputArchive : public InputArchive<JSONInputArchive>
- {
- private:
- typedef rapidjson::GenericReadStream ReadStream;
- typedef rapidjson::GenericValue<rapidjson::UTF8<>> JSONValue;
- typedef JSONValue::ConstMemberIterator MemberIterator;
- typedef JSONValue::ConstValueIterator ValueIterator;
- typedef rapidjson::Document::GenericValue GenericValue;
-
- public:
- /*! @name Common Functionality
- Common use cases for directly interacting with an JSONInputArchive */
- //! @{
-
- //! Construct, reading from the provided stream
- /*! @param stream The stream to read from */
- JSONInputArchive(std::istream & stream) :
- InputArchive<JSONInputArchive>(this),
- itsNextName( nullptr ),
- itsReadStream(stream)
- {
- itsDocument.ParseStream<0>(itsReadStream);
- itsIteratorStack.emplace_back(itsDocument.MemberBegin(), itsDocument.MemberEnd());
- }
-
- //! Loads some binary data, encoded as a base64 string
- /*! This will automatically start and finish a node to load the data, and can be called directly by
- users.
-
- Note that this follows the same ordering rules specified in the class description in regards
- to loading in/out of order */
- void loadBinaryValue( void * data, size_t size, const char * name = nullptr )
- {
- itsNextName = name;
-
- std::string encoded;
- loadValue( encoded );
- auto decoded = base64::decode( encoded );
-
- if( size != decoded.size() )
- throw Exception("Decoded binary data size does not match specified size");
-
- std::memcpy( data, decoded.data(), decoded.size() );
- itsNextName = nullptr;
- };
-
- // Intel Added this as a custom parsing hook for the AttributeValue map
- void loadAttributeValues(std::map<std::string, OC::AttributeValue>& map);
-
- private:
- //! @}
- /*! @name Internal Functionality
- Functionality designed for use by those requiring control over the inner mechanisms of
- the JSONInputArchive */
- //! @{
-
- //! An internal iterator that handles both array and object types
- /*! This class is a variant and holds both types of iterators that
- rapidJSON supports - one for arrays and one for objects. */
- class Iterator
- {
- public:
- friend class cereal::JSONInputArchive;
- Iterator() : itsIndex( 0 ), itsType(Null_) {}
-
- Iterator(MemberIterator begin, MemberIterator end) :
- itsMemberItBegin(begin), itsMemberItEnd(end), itsIndex(0), itsType(Member)
- { }
-
- Iterator(ValueIterator begin, ValueIterator end) :
- itsValueItBegin(begin), itsValueItEnd(end), itsIndex(0), itsType(Value)
- { }
-
- //! Advance to the next node
- Iterator & operator++()
- {
- ++itsIndex;
- return *this;
- }
-
- //! Get the value of the current node
- GenericValue const & value()
- {
- switch(itsType)
- {
- case Value : return itsValueItBegin[itsIndex];
- case Member: return itsMemberItBegin[itsIndex].value;
- default: throw cereal::Exception("Invalid Iterator Type!");
- }
- }
-
- //! Get the name of the current node, or nullptr if it has no name
- const char * name() const
- {
- if( itsType == Member && (itsMemberItBegin + itsIndex) != itsMemberItEnd )
- return itsMemberItBegin[itsIndex].name.GetString();
- else
- return nullptr;
- }
-
- //! Adjust our position such that we are at the node with the given name
- /*! @throws Exception if no such named node exists */
- inline void search( const char * searchName )
- {
- const auto len = std::strlen( searchName );
- size_t index = 0;
- for( auto it = itsMemberItBegin; it != itsMemberItEnd; ++it, ++index )
- if( std::strncmp( searchName, it->name.GetString(), len ) == 0 )
- {
- itsIndex = index;
- return;
- }
-
- throw Exception("JSON Parsing failed - provided NVP not found");
- }
-
- private:
- MemberIterator itsMemberItBegin, itsMemberItEnd; //!< The member iterator (object)
- ValueIterator itsValueItBegin, itsValueItEnd; //!< The value iterator (array)
- size_t itsIndex; //!< The current index of this iterator
- enum Type {Value, Member, Null_} itsType; //!< Whether this holds values (array) or members (objects) or nothing
- };
-
- //! Searches for the expectedName node if it doesn't match the actualName
- /*! This needs to be called before every load or node start occurs. This function will
- check to see if an NVP has been provided (with setNextName) and if so, see if that name matches the actual
- next name given. If the names do not match, it will search in the current level of the JSON for that name.
- If the name is not found, an exception will be thrown.
-
- Resets the NVP name after called.
-
- @throws Exception if an expectedName is given and not found */
- inline void search()
- {
- // The name an NVP provided with setNextName()
- if( itsNextName )
- {
- // The actual name of the current node
- auto const actualName = itsIteratorStack.back().name();
-
- // Do a search if we don't see a name coming up, or if the names don't match
- if( !actualName || std::strcmp( itsNextName, actualName ) != 0 )
- itsIteratorStack.back().search( itsNextName );
- }
-
- itsNextName = nullptr;
- }
-
- public:
- //! Starts a new node, going into its proper iterator
- /*! This places an iterator for the next node to be parsed onto the iterator stack. If the next
- node is an array, this will be a value iterator, otherwise it will be a member iterator.
-
- By default our strategy is to start with the document root node and then recursively iterate through
- all children in the order they show up in the document.
- We don't need to know NVPs to do this; we'll just blindly load in the order things appear in.
-
- If we were given an NVP, we will search for it if it does not match our the name of the next node
- that would normally be loaded. This functionality is provided by search(). */
- void startNode()
- {
- search();
-
- if(itsIteratorStack.back().value().IsArray())
- itsIteratorStack.emplace_back(itsIteratorStack.back().value().Begin(), itsIteratorStack.back().value().End());
- else
- itsIteratorStack.emplace_back(itsIteratorStack.back().value().MemberBegin(), itsIteratorStack.back().value().MemberEnd());
- }
-
- //! Finishes the most recently started node
- void finishNode()
- {
- itsIteratorStack.pop_back();
- ++itsIteratorStack.back();
- }
-
- //! Sets the name for the next node created with startNode
- void setNextName( const char * name )
- {
- itsNextName = name;
- }
-
- //! Loads a value from the current node - small signed overload
- template<class T> inline
- typename std::enable_if<std::is_signed<T>::value && sizeof(T) < sizeof(int64_t), void>::type
- loadValue(T & val)
- {
- search();
-
- val = itsIteratorStack.back().value().GetInt();
- ++itsIteratorStack.back();
- }
-
- //! Loads a value from the current node - small unsigned overload
- template<class T> inline
- typename std::enable_if<(std::is_unsigned<T>::value && sizeof(T) < sizeof(uint64_t)) &&
- !std::is_same<bool, T>::value, void>::type
- loadValue(T & val)
- {
- search();
-
- val = itsIteratorStack.back().value().GetUint();
- ++itsIteratorStack.back();
- }
-
- //! Loads a value from the current node - bool overload
- void loadValue(bool & val) { search(); val = itsIteratorStack.back().value().GetBool_(); ++itsIteratorStack.back(); }
- //! Loads a value from the current node - int64 overload
- void loadValue(int64_t & val) { search(); val = itsIteratorStack.back().value().GetInt64(); ++itsIteratorStack.back(); }
- //! Loads a value from the current node - uint64 overload
- void loadValue(uint64_t & val) { search(); val = itsIteratorStack.back().value().GetUint64(); ++itsIteratorStack.back(); }
- //! Loads a value from the current node - float overload
- void loadValue(float & val) { search(); val = static_cast<float>(itsIteratorStack.back().value().GetDouble()); ++itsIteratorStack.back(); }
- //! Loads a value from the current node - double overload
- void loadValue(double & val) { search(); val = itsIteratorStack.back().value().GetDouble(); ++itsIteratorStack.back(); }
- //! Loads a value from the current node - string overload
- void loadValue(std::string & val) { search(); val = itsIteratorStack.back().value().GetString(); ++itsIteratorStack.back(); }
-
- private:
- //! Convert a string to a long long
- void stringToNumber( std::string const & str, long long & val ) { val = std::stoll( str ); }
- //! Convert a string to an unsigned long long
- void stringToNumber( std::string const & str, unsigned long long & val ) { val = std::stoull( str ); }
- //! Convert a string to a long double
- void stringToNumber( std::string const & str, long double & val ) { val = std::stold( str ); }
-
- public:
- //! Loads a value from the current node - long double and long long overloads
- template<class T> inline
- typename std::enable_if<std::is_arithmetic<T>::value &&
- !std::is_same<T, long>::value &&
- !std::is_same<T, unsigned long>::value &&
- !std::is_same<T, std::int64_t>::value &&
- !std::is_same<T, std::uint64_t>::value &&
- (sizeof(T) >= sizeof(long double) || sizeof(T) >= sizeof(long long)), void>::type
- loadValue(T & val)
- {
- std::string encoded;
- loadValue( encoded );
- stringToNumber( encoded, val );
- }
-
- //! Loads the size for a SizeTag
- void loadSize(size_type & size)
- {
- size = (itsIteratorStack.rbegin() + 1)->value().Size();
- }
-
- //! @}
-
- private:
- const char * itsNextName; //!< Next name set by NVP
- ReadStream itsReadStream; //!< Rapidjson write stream
- std::vector<Iterator> itsIteratorStack; //!< 'Stack' of rapidJSON iterators
- rapidjson::Document itsDocument; //!< Rapidjson document
- };
-
- // ######################################################################
- // JSONArchive prologue and epilogue functions
- // ######################################################################
-
- // ######################################################################
- //! Prologue for NVPs for JSON archives
- /*! NVPs do not start or finish nodes - they just set up the names */
- template <class T> inline
- void prologue( JSONOutputArchive &, NameValuePair<T> const & )
- { }
-
- //! Prologue for NVPs for JSON archives
- template <class T> inline
- void prologue( JSONInputArchive &, NameValuePair<T> const & )
- { }
-
- // ######################################################################
- //! Epilogue for NVPs for JSON archives
- /*! NVPs do not start or finish nodes - they just set up the names */
- template <class T> inline
- void epilogue( JSONOutputArchive &, NameValuePair<T> const & )
- { }
-
- //! Epilogue for NVPs for JSON archives
- /*! NVPs do not start or finish nodes - they just set up the names */
- template <class T> inline
- void epilogue( JSONInputArchive &, NameValuePair<T> const & )
- { }
-
- // ######################################################################
- //! Prologue for SizeTags for JSON archives
- /*! SizeTags are strictly ignored for JSON, they just indicate
- that the current node should be made into an array */
- template <class T> inline
- void prologue( JSONOutputArchive & ar, SizeTag<T> const & )
- {
- ar.makeArray();
- }
-
- //! Prologue for SizeTags for JSON archives
- template <class T> inline
- void prologue( JSONInputArchive &, SizeTag<T> const & )
- { }
-
- // ######################################################################
- //! Epilogue for SizeTags for JSON archives
- /*! SizeTags are strictly ignored for JSON */
- template <class T> inline
- void epilogue( JSONOutputArchive &, SizeTag<T> const & )
- { }
-
- //! Epilogue for SizeTags for JSON archives
- template <class T> inline
- void epilogue( JSONInputArchive &, SizeTag<T> const & )
- { }
-
- // ######################################################################
- //! Prologue for all other types for JSON archives (except minimal types)
- /*! Starts a new node, named either automatically or by some NVP,
- that may be given data by the type about to be archived
-
- Minimal types do not start or finish nodes */
- template <class T> inline
- typename std::enable_if<!std::is_arithmetic<T>::value &&
- !traits::has_minimal_output_serialization<T, JSONOutputArchive>::value, void>::type
- prologue( JSONOutputArchive & ar, T const & )
- {
- ar.startNode();
- }
-
- //! Prologue for all other types for JSON archives
- template <class T> inline
- typename std::enable_if<!std::is_arithmetic<T>::value &&
- !traits::has_minimal_input_serialization<T, JSONOutputArchive>::value, void>::type
- prologue( JSONInputArchive & ar, T const & )
- {
- ar.startNode();
- }
-
- // ######################################################################
- //! Epilogue for all other types other for JSON archives (except minimal types
- /*! Finishes the node created in the prologue
-
- Minimal types do not start or finish nodes */
- template <class T> inline
- typename std::enable_if<!std::is_arithmetic<T>::value &&
- !traits::has_minimal_output_serialization<T, JSONOutputArchive>::value, void>::type
- epilogue( JSONOutputArchive & ar, T const & )
- {
- ar.finishNode();
- }
-
- //! Epilogue for all other types other for JSON archives
- template <class T> inline
- typename std::enable_if<!std::is_arithmetic<T>::value &&
- !traits::has_minimal_input_serialization<T, JSONOutputArchive>::value, void>::type
- epilogue( JSONInputArchive & ar, T const & )
- {
- ar.finishNode();
- }
-
- // ######################################################################
- //! Prologue for arithmetic types for JSON archives
- template <class T> inline
- typename std::enable_if<std::is_arithmetic<T>::value, void>::type
- prologue( JSONOutputArchive & ar, T const & )
- {
- ar.writeName();
- }
-
- //! Prologue for arithmetic types for JSON archives
- template <class T> inline
- typename std::enable_if<std::is_arithmetic<T>::value, void>::type
- prologue( JSONInputArchive &, T const & )
- { }
-
- // ######################################################################
- //! Epilogue for arithmetic types for JSON archives
- template <class T> inline
- typename std::enable_if<std::is_arithmetic<T>::value, void>::type
- epilogue( JSONOutputArchive &, T const & )
- { }
-
- //! Epilogue for arithmetic types for JSON archives
- template <class T> inline
- typename std::enable_if<std::is_arithmetic<T>::value, void>::type
- epilogue( JSONInputArchive &, T const & )
- { }
-
- // ######################################################################
- //! Prologue for strings for JSON archives
- template<class CharT, class Traits, class Alloc> inline
- void prologue(JSONOutputArchive & ar, std::basic_string<CharT, Traits, Alloc> const &)
- {
- ar.writeName();
- }
-
- //! Prologue for strings for JSON archives
- template<class CharT, class Traits, class Alloc> inline
- void prologue(JSONInputArchive &, std::basic_string<CharT, Traits, Alloc> const &)
- { }
-
- // ######################################################################
- //! Epilogue for strings for JSON archives
- template<class CharT, class Traits, class Alloc> inline
- void epilogue(JSONOutputArchive &, std::basic_string<CharT, Traits, Alloc> const &)
- { }
-
- //! Epilogue for strings for JSON archives
- template<class CharT, class Traits, class Alloc> inline
- void epilogue(JSONInputArchive &, std::basic_string<CharT, Traits, Alloc> const &)
- { }
-
- // ######################################################################
- // Common JSONArchive serialization functions
- // ######################################################################
-
- //! Serializing NVP types to JSON
- template <class T> inline
- void save( JSONOutputArchive & ar, NameValuePair<T> const & t )
- {
- ar.setNextName( t.name );
- ar( t.value );
- }
-
- template <class T> inline
- void load( JSONInputArchive & ar, NameValuePair<T> & t )
- {
- ar.setNextName( t.name );
- ar( t.value );
- }
-
- //! Saving for arithmetic to JSON
- template<class T> inline
- typename std::enable_if<std::is_arithmetic<T>::value, void>::type
- save(JSONOutputArchive & ar, T const & t)
- {
- ar.saveValue( t );
- }
-
- //! Loading arithmetic from JSON
- template<class T> inline
- typename std::enable_if<std::is_arithmetic<T>::value, void>::type
- load(JSONInputArchive & ar, T & t)
- {
- ar.loadValue( t );
- }
-
- //! saving string to JSON
- template<class CharT, class Traits, class Alloc> inline
- void save(JSONOutputArchive & ar, std::basic_string<CharT, Traits, Alloc> const & str)
- {
- ar.saveValue( str );
- }
-
- //! loading string from JSON
- template<class CharT, class Traits, class Alloc> inline
- void load(JSONInputArchive & ar, std::basic_string<CharT, Traits, Alloc> & str)
- {
- ar.loadValue( str );
- }
-
- // ######################################################################
- //! Saving SizeTags to JSON
- template <class T> inline
- void save( JSONOutputArchive &, SizeTag<T> const & )
- {
- // nothing to do here, we don't explicitly save the size
- }
-
- //! Loading SizeTags from JSON
- template <class T> inline
- void load( JSONInputArchive & ar, SizeTag<T> & st )
- {
- ar.loadSize( st.size );
- }
-} // namespace cereal
-
-// register archives for polymorphic support
-CEREAL_REGISTER_ARCHIVE(cereal::JSONInputArchive)
-CEREAL_REGISTER_ARCHIVE(cereal::JSONOutputArchive)
-
-#endif // CEREAL_ARCHIVES_JSON_HPP_
const std::string& uri,
const HeaderOptions& headerOptions, QualityOfService QoS)
{return OC_STACK_NOTIMPL;}
-
+
virtual OCStackResult SubscribePresence(
OCDoHandle* handle,
const std::string& host,
#define _RESOURCE_INIT_EXCEPTION_H_
#include <stdexcept>
-#include <ocstack.h>
#include "StringConstants.h"
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";
+ static const std::string DEVICEIDKEY = "di";
+ static const std::string LINKS = "links";
+
}
}
['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp'])
liboc_logger_env.InstallTarget([liboc_logger_core, liboc_logger], 'liboc_logger')
+liboc_logger_env.UserInstallTargetLib([liboc_logger_core, liboc_logger], 'liboc_logger')
if target_os not in ['ios', 'android']:
SConscript('examples/SConscript')
+++ /dev/null
-From 17300ee96e42f8848d27db6fc97f04de293662d8 Mon Sep 17 00:00:00 2001
-From: Erich Keane <erich.keane@intel.com>
-Date: Thu, 6 Nov 2014 14:37:00 -0800
-Subject: [PATCH] Get this to work on g++4.6.3
-
----
- include/cereal/cereal.hpp | 2 +-
- include/cereal/details/helpers.hpp | 32 ++++++++--------
- include/cereal/details/traits.hpp | 61 +++++++++++++++++-------------
- include/cereal/external/rapidjson/reader.h | 13 ++-----
- include/cereal/external/rapidjson/writer.h | 12 ++----
- include/cereal/types/common.hpp | 19 +++++++---
- include/cereal/types/memory.hpp | 10 ++---
- 7 files changed, 77 insertions(+), 72 deletions(-)
-
-diff --git a/include/cereal/cereal.hpp b/include/cereal/cereal.hpp
-index b2858af..a219729 100644
---- a/include/cereal/cereal.hpp
-+++ b/include/cereal/cereal.hpp
-@@ -856,7 +856,7 @@ namespace cereal
- std::uint32_t version;
-
- process( make_nvp<ArchiveType>("cereal_class_version", version) );
-- itsVersionedTypes.emplace_hint( lookupResult, hash, version );
-+ itsVersionedTypes.insert( lookupResult, std::pair<std::size_t, std::uint32_t>(hash, version) );
-
- return version;
- }
-diff --git a/include/cereal/details/helpers.hpp b/include/cereal/details/helpers.hpp
-index e792d44..60e13c8 100644
---- a/include/cereal/details/helpers.hpp
-+++ b/include/cereal/details/helpers.hpp
-@@ -55,7 +55,7 @@ namespace cereal
- /*! To ensure compatability between 32, 64, etc bit machines, we need to use
- * a fixed size type instead of size_t, which may vary from machine to
- * machine. */
-- using size_type = uint64_t;
-+ typedef uint64_t size_type;
-
- // forward decls
- class BinaryOutputArchive;
-@@ -138,12 +138,12 @@ namespace cereal
- // otherwise, we store a reference. If we were passed an array, don't
- // decay the type - keep it as an array, and then proceed as normal
- // with the RValue business
-- using DT = typename std::conditional<std::is_array<typename std::remove_reference<T>::type>::value,
-+ typedef typename std::conditional<std::is_array<typename std::remove_reference<T>::type>::value,
- typename std::remove_cv<T>::type,
-- typename std::decay<T>::type>::type;
-- using Type = typename std::conditional<std::is_rvalue_reference<T>::value,
-+ typename std::decay<T>::type>::type DT;
-+ typedef typename std::conditional<std::is_rvalue_reference<T>::value,
- DT,
-- typename std::add_lvalue_reference<DT>::type>::type;
-+ typename std::add_lvalue_reference<DT>::type>::type Type;
- // prevent nested nvps
- static_assert( !std::is_base_of<detail::NameValuePairCore, T>::value,
- "Cannot pair a name to a NameValuePair" );
-@@ -207,9 +207,9 @@ namespace cereal
- {
- //! Internally store the pointer as a void *, keeping const if created with
- //! a const pointer
-- using PT = typename std::conditional<std::is_const<typename std::remove_pointer<T>::type>::value,
-+ typedef typename std::conditional<std::is_const<typename std::remove_pointer<T>::type>::value,
- const void *,
-- void *>::type;
-+ void *>::type PT;
-
- BinaryData( T && d, uint64_t s ) : data(d), size(s) {}
-
-@@ -248,10 +248,10 @@ namespace cereal
- private:
- // If we get passed an RValue, we'll just make a local copy if it here
- // otherwise, we store a reference
-- using DT = typename std::decay<T>::type;
-- using Type = typename std::conditional<std::is_rvalue_reference<T>::value,
-+ typedef typename std::decay<T>::type DT;
-+ typedef typename std::conditional<std::is_rvalue_reference<T>::value,
- DT,
-- typename std::add_lvalue_reference<DT>::type>::type;
-+ typename std::add_lvalue_reference<DT>::type>::type Type;
-
- public:
- SizeTag( T && sz ) : size(const_cast<Type>(sz)) {}
-@@ -283,17 +283,17 @@ namespace cereal
- template <class Key, class Value>
- struct MapItem
- {
-- using DecayKey = typename std::decay<Key>::type;
-- using KeyType = typename std::conditional<
-+ typedef typename std::decay<Key>::type DecayKey;
-+ typedef typename std::conditional<
- std::is_rvalue_reference<Key>::value,
- DecayKey,
-- typename std::add_lvalue_reference<DecayKey>::type>::type;
-+ typename std::add_lvalue_reference<DecayKey>::type>::type KeyType;
-
-- using DecayValue = typename std::decay<Value>::type;
-- using ValueType = typename std::conditional<
-+ typedef typename std::decay<Value>::type DecayValue;
-+ typedef typename std::conditional<
- std::is_rvalue_reference<Value>::value,
- DecayValue,
-- typename std::add_lvalue_reference<DecayValue>::type>::type;
-+ typename std::add_lvalue_reference<DecayValue>::type>::type ValueType;
-
- //! Construct a MapItem from a key and a value
- /*! @internal */
-diff --git a/include/cereal/details/traits.hpp b/include/cereal/details/traits.hpp
-index 871886f..011054b 100644
---- a/include/cereal/details/traits.hpp
-+++ b/include/cereal/details/traits.hpp
-@@ -411,12 +411,12 @@ namespace cereal
- };
-
- template <class T, class A, bool Valid>
-- struct get_member_save_minimal_type { using type = void; };
-+ struct get_member_save_minimal_type { typedef void type; };
-
- template <class T, class A>
- struct get_member_save_minimal_type<T, A, true>
- {
-- using type = decltype( cereal::access::member_save_minimal( std::declval<A const &>(), std::declval<T const &>() ) );
-+ typedef decltype( cereal::access::member_save_minimal( std::declval<A const &>(), std::declval<T const &>() ) ) type;
- };
- } // end namespace detail
-
-@@ -428,7 +428,7 @@ namespace cereal
- "cereal detected a non-const member save_minimal. "
- "save_minimal member functions must always be const" );
-
-- using type = typename detail::get_member_save_minimal_type<T, A, check::value>::type;
-+ typedef typename detail::get_member_save_minimal_type<T, A, check::value>::type type;
- static_assert( (check::value && is_minimal_type<type>::value) || !check::value,
- "cereal detected a member save_minimal with an invalid return type. "
- "return type must be arithmetic or string" );
-@@ -473,12 +473,12 @@ namespace cereal
- };
-
- template <class T, class A, bool Valid>
-- struct get_member_versioned_save_minimal_type { using type = void; };
-+ struct get_member_versioned_save_minimal_type { typedef void type; };
-
- template <class T, class A>
- struct get_member_versioned_save_minimal_type<T, A, true>
- {
-- using type = decltype( cereal::access::member_save_minimal( std::declval<A const &>(), std::declval<T const &>(), 0 ) );
-+ typedef decltype( cereal::access::member_save_minimal( std::declval<A const &>(), std::declval<T const &>(), 0 ) ) type;
- };
- } // end namespace detail
-
-@@ -490,7 +490,7 @@ namespace cereal
- "cereal detected a versioned non-const member save_minimal. "
- "save_minimal member functions must always be const" );
-
-- using type = typename detail::get_member_versioned_save_minimal_type<T, A, check::value>::type;
-+ typedef typename detail::get_member_versioned_save_minimal_type<T, A, check::value>::type type;
- static_assert( (check::value && is_minimal_type<type>::value) || !check::value,
- "cereal detected a versioned member save_minimal with an invalid return type. "
- "return type must be arithmetic or string" );
-@@ -519,12 +519,12 @@ namespace cereal
- };
-
- template <class T, class A, bool Valid>
-- struct get_non_member_save_minimal_type { using type = void; };
-+ struct get_non_member_save_minimal_type { typedef void type; };
-
- template <class T, class A>
- struct get_non_member_save_minimal_type <T, A, true>
- {
-- using type = decltype( save_minimal( std::declval<A const &>(), std::declval<T const &>() ) );
-+ typedef decltype( save_minimal( std::declval<A const &>(), std::declval<T const &>() ) ) type;
- };
- } // end namespace detail
-
-@@ -536,7 +536,7 @@ namespace cereal
- "cereal detected a non-const type parameter in non-member save_minimal. "
- "save_minimal non-member functions must always pass their types as const" );
-
-- using type = typename detail::get_non_member_save_minimal_type<T, A, check::value>::type;
-+ typedef typename detail::get_non_member_save_minimal_type<T, A, check::value>::type type;
- static_assert( (check::value && is_minimal_type<type>::value) || !check::value,
- "cereal detected a non-member save_minimal with an invalid return type. "
- "return type must be arithmetic or string" );
-@@ -565,12 +565,12 @@ namespace cereal
- };
-
- template <class T, class A, bool Valid>
-- struct get_non_member_versioned_save_minimal_type { using type = void; };
-+ struct get_non_member_versioned_save_minimal_type { typedef void type; };
-
- template <class T, class A>
- struct get_non_member_versioned_save_minimal_type <T, A, true>
- {
-- using type = decltype( save_minimal( std::declval<A const &>(), std::declval<T const &>(), 0 ) );
-+ typedef decltype( save_minimal( std::declval<A const &>(), std::declval<T const &>(), 0 ) ) type;
- };
- } // end namespace detail
-
-@@ -582,7 +582,7 @@ namespace cereal
- "cereal detected a non-const type parameter in versioned non-member save_minimal. "
- "save_minimal non-member functions must always pass their types as const" );
-
-- using type = typename detail::get_non_member_versioned_save_minimal_type<T, A, check::value>::type;
-+ typedef typename detail::get_non_member_versioned_save_minimal_type<T, A, check::value>::type type;
- static_assert( (check::value && is_minimal_type<type>::value) || !check::value,
- "cereal detected a non-member versioned save_minimal with an invalid return type. "
- "return type must be arithmetic or string" );
-@@ -608,7 +608,7 @@ namespace cereal
- template <class Source>
- struct NoConvertConstRef : NoConvertBase
- {
-- using type = Source; //!< Used to get underlying type easily
-+ typedef Source type; //!< Used to get underlying type easily
-
- template <class Dest, class = typename std::enable_if<std::is_same<Source, Dest>::value>::type>
- operator Dest () = delete;
-@@ -626,7 +626,7 @@ namespace cereal
- template <class Source>
- struct NoConvertRef : NoConvertBase
- {
-- using type = Source; //!< Used to get underlying type easily
-+ typedef Source type; //!< Used to get underlying type easily
-
- template <class Dest, class = typename std::enable_if<std::is_same<Source, Dest>::value>::type>
- operator Dest () = delete;
-@@ -698,7 +698,7 @@ namespace cereal
- "cereal detected member load_minimal but no valid member save_minimal. "
- "cannot evaluate correctness of load_minimal without valid save_minimal." );
-
-- using SaveType = typename detail::get_member_save_minimal_type<T, A, true>::type;
-+ typedef typename detail::get_member_save_minimal_type<T, A, true>::type SaveType;
- const static bool value = has_member_load_minimal_impl<T, A>::value;
- const static bool valid = has_member_load_minimal_type_impl<T, A, SaveType>::value;
-
-@@ -759,7 +759,7 @@ namespace cereal
- "cereal detected member versioned load_minimal but no valid member versioned save_minimal. "
- "cannot evaluate correctness of load_minimal without valid save_minimal." );
-
-- using SaveType = typename detail::get_member_versioned_save_minimal_type<T, A, true>::type;
-+ typedef typename detail::get_member_versioned_save_minimal_type<T, A, true>::type SaveType;
- const static bool value = has_member_versioned_load_minimal_impl<T, A>::value;
- const static bool valid = has_member_versioned_load_minimal_type_impl<T, A, SaveType>::value;
-
-@@ -814,8 +814,8 @@ namespace cereal
- "cereal detected non-member load_minimal but no valid non-member save_minimal. "
- "cannot evaluate correctness of load_minimal without valid save_minimal." );
-
-- using SaveType = typename detail::get_non_member_save_minimal_type<T, A, true>::type;
-- using check = has_non_member_load_minimal_impl<T, A, SaveType>;
-+ typedef typename detail::get_non_member_save_minimal_type<T, A, true>::type SaveType;
-+ typedef has_non_member_load_minimal_impl<T, A, SaveType> check;
- static const bool value = check::exists;
-
- static_assert( check::valid || !check::exists, "cereal detected different types in corresponding non-member load_minimal and save_minimal functions. "
-@@ -866,8 +866,8 @@ namespace cereal
- "cereal detected non-member versioned load_minimal but no valid non-member versioned save_minimal. "
- "cannot evaluate correctness of load_minimal without valid save_minimal." );
-
-- using SaveType = typename detail::get_non_member_versioned_save_minimal_type<T, A, true>::type;
-- using check = has_non_member_versioned_load_minimal_impl<T, A, SaveType>;
-+ typedef typename detail::get_non_member_versioned_save_minimal_type<T, A, true>::type SaveType;
-+ typedef has_non_member_versioned_load_minimal_impl<T, A, SaveType> check;;
- static const bool value = check::exists;
-
- static_assert( check::valid || !check::exists, "cereal detected different types in corresponding non-member versioned load_minimal and save_minimal functions. "
-@@ -1182,9 +1182,16 @@ namespace cereal
- };
- }
-
-+ // works around the lack of decltype inheritance in GCC 4.6
-+ template<class T>
-+ struct shared_wrapper
-+ {
-+ typedef decltype(detail::shared_from_this_wrapper::check(std::declval<T>())) type;
-+
-+ };
- //! Determine if T or any base class of T has inherited from std::enable_shared_from_this
- template<class T>
-- struct has_shared_from_this : decltype(detail::shared_from_this_wrapper::check(std::declval<T>()))
-+ struct has_shared_from_this : shared_wrapper<T>::type
- { };
-
- //! Get the type of the base class of T which inherited from std::enable_shared_from_this
-@@ -1192,10 +1199,10 @@ namespace cereal
- struct get_shared_from_this_base
- {
- private:
-- using PtrType = decltype(detail::shared_from_this_wrapper::get(std::declval<T>()));
-+ typedef decltype(detail::shared_from_this_wrapper::get(std::declval<T>())) PtrType;
- public:
- //! The type of the base of T that inherited from std::enable_shared_from_this
-- using type = typename std::decay<typename PtrType::element_type>::type;
-+ typedef typename std::decay<typename PtrType::element_type>::type type;
- };
-
- // ######################################################################
-@@ -1209,14 +1216,14 @@ namespace cereal
- template <class T, bool IsCerealMinimalTrait = std::is_base_of<detail::NoConvertBase, T>::value>
- struct strip_minimal
- {
-- using type = T;
-+ typedef T type;
- };
-
- //! Specialization for types wrapped in a NoConvert
- template <class T>
- struct strip_minimal<T, true>
- {
-- using type = typename T::type;
-+ typedef typename T::type type;
- };
- } // namespace traits
-
-@@ -1232,10 +1239,12 @@ namespace cereal
- { return nullptr; }
- };
-
-+ template<class T>
-+ struct is_default_constructible : std::is_constructible<T>{};
- template <class T, class A>
- struct Construct<T, A, false, false>
- {
-- static_assert( std::is_default_constructible<T>::value,
-+ static_assert( is_default_constructible<T>::value,
- "Trying to serialize a an object with no default constructor. \n\n "
- "Types must either be default constructible or define either a member or non member Construct function. \n "
- "Construct functions generally have the signature: \n\n "
-diff --git a/include/cereal/external/rapidjson/reader.h b/include/cereal/external/rapidjson/reader.h
-index 7790907..3ee838c 100644
---- a/include/cereal/external/rapidjson/reader.h
-+++ b/include/cereal/external/rapidjson/reader.h
-@@ -402,20 +402,13 @@ private:
- }
-
- // cereal Temporary until constexpr support is added in RTM
--#ifdef _MSC_VER
-+//#ifdef _MSC_VER
- template <class Ch>
- bool characterOk( Ch c )
- {
- return c < 256;
- }
--
-- template <>
-- bool characterOk<char>( Ch )
-- {
-- return true;
-- }
--
--#else
-+/*#else
- // As part of a fix for GCC 4.7
- template <class T>
- static constexpr int to_int( T t ){ return t; }
-@@ -432,7 +425,7 @@ private:
- characterOk(Ch c)
- { return c < 256; }
- #endif
--
-+*/
- // Parse string, handling the prefix and suffix double quotes and escaping.
- template<unsigned parseFlags, typename Stream, typename Handler>
- void ParseString(Stream& stream, Handler& handler) {
-diff --git a/include/cereal/external/rapidjson/writer.h b/include/cereal/external/rapidjson/writer.h
-index 0f87255..e02c27a 100644
---- a/include/cereal/external/rapidjson/writer.h
-+++ b/include/cereal/external/rapidjson/writer.h
-@@ -177,20 +177,14 @@ protected:
- }
-
- // cereal Temporary until constexpr support is added in RTM
--#ifdef _MSC_VER
-+//#ifdef _MSC_VER
- template <class Ch>
- bool characterOk( Ch c )
- {
- return c < 256;
- }
-
-- template <>
-- bool characterOk<char>( Ch )
-- {
-- return true;
-- }
--
--#else
-+/*#else
- // As part of a fix for GCC 4.7
- template <class T>
- static constexpr int to_int( T t ){ return t; }
-@@ -206,7 +200,7 @@ protected:
- typename std::enable_if< to_int(std::numeric_limits<Ch>::max()) >= to_int(256), bool>::type
- characterOk(Ch c)
- { return c < 256; }
--#endif
-+#endif*/
-
- //! \todo Optimization with custom double-to-string converter.
- void WriteDouble(double d) {
-diff --git a/include/cereal/types/common.hpp b/include/cereal/types/common.hpp
-index abb8bfd..5c014cd 100644
---- a/include/cereal/types/common.hpp
-+++ b/include/cereal/types/common.hpp
-@@ -55,6 +55,15 @@ namespace cereal
-
- namespace
- {
-+ template<class en>
-+ struct underlying_type
-+ {
-+ typedef typename std::conditional<
-+ en(-1)<en(0),
-+ typename std::make_signed<en>::type,
-+ typename std::make_unsigned<en>::type
-+ > ::type type;
-+ };
- //! Gets the underlying type of an enum
- /*! @internal */
- template <class T, bool IsEnum>
-@@ -64,7 +73,7 @@ namespace cereal
- /*! Specialization for when we actually have an enum
- @internal */
- template <class T>
-- struct enum_underlying_type<T, true> { using type = typename std::underlying_type<T>::type; };
-+ struct enum_underlying_type<T, true> { typedef typename underlying_type<T>::type type; };
- } // anon namespace
-
- //! Checks if a type is an enum
-@@ -78,13 +87,13 @@ namespace cereal
- class is_enum
- {
- private:
-- using DecayedT = typename std::decay<T>::type;
-- using StrippedT = typename ::cereal::traits::strip_minimal<DecayedT>::type;
-+ typedef typename std::decay<T>::type DecayedT;
-+ typedef typename ::cereal::traits::strip_minimal<DecayedT>::type StrippedT;
-
- public:
- static const bool value = std::is_enum<StrippedT>::value;
-- using type = StrippedT;
-- using base_type = typename enum_underlying_type<StrippedT, value>::type;
-+ typedef StrippedT type;
-+ typedef typename enum_underlying_type<StrippedT, value>::type base_type;
- };
- }
-
-diff --git a/include/cereal/types/memory.hpp b/include/cereal/types/memory.hpp
-index bf56c92..d2357ff 100644
---- a/include/cereal/types/memory.hpp
-+++ b/include/cereal/types/memory.hpp
-@@ -115,9 +115,9 @@ namespace cereal
- class EnableSharedStateHelper
- {
- // typedefs for parent type and storage type
-- using BaseType = typename ::cereal::traits::get_shared_from_this_base<T>::type;
-- using ParentType = std::enable_shared_from_this<BaseType>;
-- using StorageType = typename std::aligned_storage<sizeof(ParentType)>::type;
-+ typedef typename ::cereal::traits::get_shared_from_this_base<T>::type BaseType;
-+ typedef std::enable_shared_from_this<BaseType> ParentType;
-+ typedef typename std::aligned_storage<sizeof(ParentType)>::type StorageType;
-
- public:
- //! Saves the state of some type inheriting from enable_shared_from_this
-@@ -257,7 +257,7 @@ namespace cereal
- {
- // Storage type for the pointer - since we can't default construct this type,
- // we'll allocate it using std::aligned_storage and use a custom deleter
-- using ST = typename std::aligned_storage<sizeof(T)>::type;
-+ typedef typename std::aligned_storage<sizeof(T)>::type ST;
-
- // Valid flag - set to true once construction finishes
- // This prevents us from calling the destructor on
-@@ -345,7 +345,7 @@ namespace cereal
- {
- // Storage type for the pointer - since we can't default construct this type,
- // we'll allocate it using std::aligned_storage
-- using ST = typename std::aligned_storage<sizeof(T)>::type;
-+ typedef typename std::aligned_storage<sizeof(T)>::type ST;
-
- // Allocate storage - note the ST type so that deleter is correct if
- // an exception is thrown before we are initialized
---
-1.9.3
-
#include "OCPlatform.h"
#include "OCResource.h"
+#include "ocpayload.h"
#include <OCSerialization.h>
using namespace std;
OCRepresentation parseGetSetCallback(OCClientResponse* clientResponse)
{
- if(clientResponse->resJSONPayload == nullptr || clientResponse->resJSONPayload[0] == '\0')
- {
+ if(clientResponse->payload == nullptr ||
+ (
+ clientResponse->payload->type != PAYLOAD_TYPE_DEVICE &&
+ clientResponse->payload->type != PAYLOAD_TYPE_PLATFORM &&
+ clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION
+ )
+ )
+ {
+ //OCPayloadDestroy(clientResponse->payload);
return OCRepresentation();
}
MessageContainer oc;
- 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);
- }
+ oc.setPayload(clientResponse->payload);
+ //OCPayloadDestroy(clientResponse->payload);
std::vector<OCRepresentation>::const_iterator it = oc.representations().begin();
if(it == oc.representations().end())
return OC_STACK_KEEP_TRANSACTION;
}
+ if(!clientResponse->payload || clientResponse->payload->type != PAYLOAD_TYPE_DISCOVERY)
+ {
+ oclog() << "listenCallback(): clientResponse payload was null or the wrong type"
+ << std::flush;
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
auto clientWrapper = context->clientWrapper.lock();
if(!clientWrapper)
return OC_STACK_KEEP_TRANSACTION;
}
- std::stringstream requestStream;
- requestStream << clientResponse->resJSONPayload;
-
- try
- {
-
- ListenOCContainer container(clientWrapper, clientResponse->devAddr,
- requestStream);
- // loop to ensure valid construction of all resources
- for(auto resource : container.Resources())
- {
- std::thread exec(context->callback, resource);
- exec.detach();
- }
-
- }
- catch(const std::exception& e)
+ ListenOCContainer container(clientWrapper, clientResponse->devAddr,
+ reinterpret_cast<OCDiscoveryPayload*>(clientResponse->payload));
+ // loop to ensure valid construction of all resources
+ for(auto resource : container.Resources())
{
- oclog() << "listenCallback failed to parse a malformed message: "
- << e.what()
- << std::endl
- << clientResponse->resJSONPayload
- << std::endl
- << clientResponse->result
- << std::flush;
- return OC_STACK_KEEP_TRANSACTION;
+ std::thread exec(context->callback, resource);
+ exec.detach();
}
+
return OC_STACK_KEEP_TRANSACTION;
}
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCHeaderOption options[MAX_HEADER_OPTIONS];
- result = OCDoResource(nullptr, OC_REST_GET,
+ result = OCDoResource(
+ nullptr, OC_REST_GET,
uri.c_str(),
&devAddr, nullptr,
CT_DEFAULT,
return ret;
}
- std::string InProcClientWrapper::assembleSetResourcePayload(const OCRepresentation& rep)
+ OCPayload* InProcClientWrapper::assembleSetResourcePayload(const OCRepresentation& rep)
{
MessageContainer ocInfo;
ocInfo.addRepresentation(rep);
- return ocInfo.getJSONRepresentation(OCInfoFormat::IncludeOC);
+ return reinterpret_cast<OCPayload*>(ocInfo.getPayload());
}
OCStackResult InProcClientWrapper::PostResourceRepresentation(
result = OCDoResource(nullptr, OC_REST_POST,
url.c_str(), &devAddr,
- assembleSetResourcePayload(rep).c_str(),
+ assembleSetResourcePayload(rep),
CT_DEFAULT,
static_cast<OCQualityOfService>(QoS),
&cbdata,
result = OCDoResource(&handle, OC_REST_PUT,
url.c_str(), &devAddr,
- assembleSetResourcePayload(rep).c_str(),
+ assembleSetResourcePayload(rep),
CT_DEFAULT,
static_cast<OCQualityOfService>(QoS),
&cbdata,
auto cLock = m_csdkLock.lock();
std::ostringstream os;
- os << host << "/oc/presence";
+ os << host << OC_RSRVD_PRESENCE_URI;;
if(!resourceType.empty())
{
else if(OC_REST_PUT == entityHandlerRequest->method)
{
pRequest->setRequestType(OC::PlatformCommands::PUT);
- pRequest->setPayload(std::string(reinterpret_cast<const char*>
- (entityHandlerRequest->reqJSONPayload)));
+ pRequest->setPayload(entityHandlerRequest->payload);
}
else if(OC_REST_POST == entityHandlerRequest->method)
{
pRequest->setRequestType(OC::PlatformCommands::POST);
- pRequest->setPayload(std::string(reinterpret_cast<const char*>
- (entityHandlerRequest->reqJSONPayload)));
+ pRequest->setPayload(entityHandlerRequest->payload);
}
else if(OC_REST_DELETE == entityHandlerRequest->method)
{
else
{
OCEntityHandlerResponse response;
- std::string payLoad = pResponse->getPayload();
+// OCRepPayload* payLoad = pResponse->getPayload();
HeaderOptions serverHeaderOptions = pResponse->getHeaderOptions();
response.requestHandle = pResponse->getRequestHandle();
response.resourceHandle = pResponse->getResourceHandle();
response.ehResult = pResponse->getResponseResult();
- response.payload = static_cast<char*>(OICMalloc(payLoad.length() + 1));
- if(!response.payload)
- {
- result = OC_STACK_NO_MEMORY;
- throw OCException(OC::Exception::NO_MEMORY, OC_STACK_NO_MEMORY);
- }
+ response.payload = reinterpret_cast<OCPayload*>(pResponse->getPayload());
- payLoad.copy(response.payload, payLoad.length());
- response.payload[payLoad.length()] = '\0';
- response.payloadSize = payLoad.length() + 1;
response.persistentBufferFlag = 0;
response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size();
static_cast<uint16_t>(it->getOptionID());
response.sendVendorSpecificHeaderOptions[i].optionLength =
(it->getOptionData()).length() + 1;
- std::copy(it->getOptionData().begin(),
- it->getOptionData().end(),
+ std::string optionData = it->getOptionData();
+ std::copy(optionData.begin(),
+ optionData.end(),
response.sendVendorSpecificHeaderOptions[i].optionData);
response.sendVendorSpecificHeaderOptions[i].optionData[it->getOptionData().length()]
= '\0';
#include "OCApi.h"
#include "OCException.h"
#include "OCUtilities.h"
+#include "ocpayload.h"
#include "oc_logger.hpp"
return result_guard(OC_STACK_ERROR);
}
- std::string payload(pResponse->getResourceRepresentation().getJSONRepresentation());
-
- return result_guard(
+ OCRepPayload* pl = pResponse->getResourceRepresentation().getPayload();
+ OCStackResult result =
OCNotifyListOfObservers(resourceHandle,
&observationIds[0], observationIds.size(),
- payload.c_str(),
- static_cast<OCQualityOfService>(QoS)));
+ pl,
+ static_cast<OCQualityOfService>(QoS));
+ OCRepPayloadDestroy(pl);
+ return result_guard(result);
}
OCResource::Ptr OCPlatform_impl::constructResourceObject(const std::string& host,
std::vector<std::string> resourceTypes = resource->getResourceTypes();
return checked_guard(m_server, &IServerWrapper::registerResource,
- std::ref(resourceHandle), resource->uri(),
+ std::ref(resourceHandle), resource->host() + resource->uri(),
resourceTypes[0]/*"core.remote"*/, DEFAULT_INTERFACE,
(EntityHandler) nullptr, resourceProperty);
}
#include <OCRepresentation.h>
#include <boost/lexical_cast.hpp>
-#include <cereal/cereal.hpp>
-#include <cereal/types/map.hpp>
-#include <cereal/types/vector.hpp>
-#include <cereal/types/utility.hpp>
-#include <OicJsonSerializer.hpp>
#include <algorithm>
+#include "ocpayload.h"
+#include "ocrandom.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
-// code needed to serialize a string=>Attribute value map
namespace OC
{
- namespace detail
+
+ void MessageContainer::setPayload(const OCPayload* rep)
{
- template<class Archive>
- class WriteAttributeValue : public boost::static_visitor<>
+ switch(rep->type)
{
- public:
- WriteAttributeValue(const std::string& name, Archive& ar)
- :m_name(name), m_archive(ar)
- {}
-
- template<class T>
- void operator()(const T& value) const
- {
- m_archive(cereal::make_nvp(m_name, value));
- }
- private:
- std::string m_name;
- Archive& m_archive;
- };
+ case PAYLOAD_TYPE_REPRESENTATION:
+ setPayload(reinterpret_cast<const OCRepPayload*>(rep));
+ break;
+ case PAYLOAD_TYPE_DEVICE:
+ setPayload(reinterpret_cast<const OCDevicePayload*>(rep));
+ break;
+ case PAYLOAD_TYPE_PLATFORM:
+ setPayload(reinterpret_cast<const OCPlatformPayload*>(rep));
+ break;
+ default:
+ throw OC::OCException("Invalid Payload type in setPayload");
+ break;
+ }
}
-}
-
-namespace cereal
-{
- // take no action when serializing the null type, because the 'save' below
- // doesn't use the visitor for this type.
- template <class Archive>
- void serialize(Archive&, OC::NullType t)
- {}
- template<class Archive>
- void save(Archive& ar, const std::map<std::string, OC::AttributeValue>& vals)
+ void MessageContainer::setPayload(const OCDevicePayload* payload)
{
- for(const auto& kv : vals)
+ OCRepresentation rep;
+ rep.setUri(payload->uri);
+ char uuidString[UUID_STRING_SIZE];
+ if(payload->sid && RAND_UUID_OK == OCConvertUuidToString(payload->sid, uuidString))
{
- const auto& k = kv.first;
- const auto& v = kv.second;
+ rep[OC_RSRVD_DEVICE_ID] = std::string(uuidString);
+ }
+ else
+ {
+ rep[OC_RSRVD_DEVICE_ID] = std::string();
+ }
+ rep[OC_RSRVD_DEVICE_NAME] = payload->deviceName ?
+ std::string(payload->deviceName) :
+ std::string();
+ rep[OC_RSRVD_SPEC_VERSION] = payload->specVersion ?
+ std::string(payload->specVersion) :
+ std::string();
+ rep[OC_RSRVD_DATA_MODEL_VERSION] = payload->dataModelVersion ?
+ std::string(payload->dataModelVersion) :
+ std::string();
+ m_reps.push_back(std::move(rep));
+ }
+
+ void MessageContainer::setPayload(const OCPlatformPayload* payload)
+ {
+ OCRepresentation rep;
+ rep.setUri(payload->uri);
+
+ rep[OC_RSRVD_PLATFORM_ID] = payload->info.platformID ?
+ std::string(payload->info.platformID) :
+ std::string();
+ rep[OC_RSRVD_MFG_NAME] = payload->info.manufacturerName ?
+ std::string(payload->info.manufacturerName) :
+ std::string();
+ rep[OC_RSRVD_MFG_URL] = payload->info.manufacturerUrl ?
+ std::string(payload->info.manufacturerUrl) :
+ std::string();
+ rep[OC_RSRVD_MODEL_NUM] = payload->info.modelNumber ?
+ std::string(payload->info.modelNumber) :
+ std::string();
+ rep[OC_RSRVD_MFG_DATE] = payload->info.dateOfManufacture ?
+ std::string(payload->info.dateOfManufacture) :
+ std::string();
+ rep[OC_RSRVD_PLATFORM_VERSION] = payload->info.platformVersion ?
+ std::string(payload->info.platformVersion) :
+ std::string();
+ rep[OC_RSRVD_OS_VERSION] = payload->info.operatingSystemVersion ?
+ std::string(payload->info.operatingSystemVersion) :
+ std::string();
+ rep[OC_RSRVD_HARDWARE_VERSION] = payload->info.hardwareVersion ?
+ std::string(payload->info.hardwareVersion) :
+ std::string();
+ rep[OC_RSRVD_FIRMWARE_VERSION] = payload->info.firmwareVersion ?
+ std::string(payload->info.firmwareVersion) :
+ std::string();
+ rep[OC_RSRVD_SUPPORT_URL] = payload->info.supportUrl ?
+ std::string(payload->info.supportUrl) :
+ std::string();
+ rep[OC_RSRVD_SYSTEM_TIME] = payload->info.systemTime ?
+ std::string(payload->info.systemTime) :
+ std::string();
+
+ m_reps.push_back(std::move(rep));
+ }
+
+ void MessageContainer::setPayload(const OCRepPayload* payload)
+ {
+ const OCRepPayload* pl = payload;
+ while(pl)
+ {
+ OCRepresentation cur;
+ cur.setPayload(pl);
+
+ pl = pl->next;
+ this->addRepresentation(cur);
+ }
+ }
- if(v.which() != OC::AttributeValueNullIndex)
+ OCRepPayload* MessageContainer::getPayload() const
+ {
+ OCRepPayload* root = nullptr;
+ for(const auto& r : representations())
+ {
+ if(!root)
{
- OC::detail::WriteAttributeValue<Archive> writer(k,ar);
- boost::apply_visitor(writer, v);
+ root = r.getPayload();
}
else
{
- ar.setNextName(k.c_str());
- ar.writeName();
- ar.saveValue();
+ OCRepPayloadAppend(root, r.getPayload());
}
}
+
+ return root;
}
- template<class Archive>
- void load(Archive& ar, std::map<std::string, OC::AttributeValue>& vals)
+ const std::vector<OCRepresentation>& MessageContainer::representations() const
{
- ar.loadAttributeValues(vals);
+ return m_reps;
+ }
+
+ void MessageContainer::addRepresentation(const OCRepresentation& rep)
+ {
+ m_reps.push_back(rep);
}
}
namespace OC
{
- typedef cereal::JSONOutputArchive OutputArchiveType;
- typedef cereal::JSONInputArchive InputArchiveType;
+ struct get_payload_array: boost::static_visitor<>
+ {
+ template<typename T>
+ void operator()(T& arr)
+ {
+ throw std::logic_error("Invalid calc_dimensions_visitor type");
+ }
+
+ template<typename T>
+ void operator()(std::vector<T>& arr)
+ {
+ root_size_calc<T>();
+ dimensions[0] = arr.size();
+ dimTotal = calcDimTotal(dimensions);
+
+ array = (void*)OICMalloc(dimTotal * root_size);
+
+ for(size_t i = 0; i < dimensions[0]; ++i)
+ {
+ copy_to_array(arr[i], array, i);
+ }
+
+ }
+ template<typename T>
+ void operator()(std::vector<std::vector<T>>& arr)
+ {
+ root_size_calc<T>();
+ dimensions[0] = arr.size();
+ for(size_t i = 0; i < arr.size(); ++i)
+ {
+ dimensions[1] = std::max(dimensions[1], arr[i].size());
+ }
+ dimTotal = calcDimTotal(dimensions);
+ array = (void*)OICCalloc(1, dimTotal * root_size);
+
+ for(size_t i = 0; i < dimensions[0]; ++i)
+ {
+ for(size_t j = 0; j < dimensions[1] && j < arr[i].size(); ++j)
+ {
+ copy_to_array(arr[i][j], array, i*dimensions[1] + j);
+ }
+ }
+ }
+ template<typename T>
+ void operator()(std::vector<std::vector<std::vector<T>>>& arr)
+ {
+ root_size_calc<T>();
+ dimensions[0] = arr.size();
+ for(size_t i = 0; i < arr.size(); ++i)
+ {
+ dimensions[1] = std::max(dimensions[1], arr[i].size());
+
+ for(size_t j = 0; j < arr[i].size(); ++j)
+ {
+ dimensions[2] = std::max(dimensions[2], arr[i][j].size());
+ }
+ }
+
+ dimTotal = calcDimTotal(dimensions);
+ array = (void*)OICCalloc(1, dimTotal * root_size);
+
+ for(size_t i = 0; i < dimensions[0]; ++i)
+ {
+ for(size_t j = 0; j < dimensions[1] && j < arr[i].size(); ++j)
+ {
+ for(size_t k = 0; k < dimensions[2] && k < arr[i][j].size(); ++k)
+ {
+ copy_to_array(arr[i][j][k], array,
+ dimensions[2] * j +
+ dimensions[2] * dimensions[1] * i +
+ k);
+ }
+ }
+ }
+ }
+
+ template<typename T>
+ void root_size_calc()
+ {
+ root_size = sizeof(T);
+ }
+
+ template<typename T>
+ void copy_to_array(T item, void* array, size_t pos)
+ {
+ ((T*)array)[pos] = item;
+ }
+
+ size_t dimensions[MAX_REP_ARRAY_DEPTH];
+ size_t root_size;
+ size_t dimTotal;
+ void* array;
+ };
+
+ template<>
+ void get_payload_array::root_size_calc<int>()
+ {
+ root_size = sizeof(int64_t);
+ }
+
+ template<>
+ void get_payload_array::root_size_calc<std::string>()
+ {
+ root_size = sizeof(char*);
+ }
+
+ template<>
+ void get_payload_array::root_size_calc<OC::OCRepresentation>()
+ {
+ root_size = sizeof(OCRepPayload*);
+ }
+
+ template<>
+ void get_payload_array::copy_to_array(int item, void* array, size_t pos)
+ {
+ ((int64_t*)array)[pos] = item;
+ }
+
+ template<>
+ void get_payload_array::copy_to_array(std::_Bit_reference br, void* array, size_t pos)
+ {
+ ((bool*)array)[pos] = static_cast<bool>(br);
+ }
- void MessageContainer::setJSONRepresentation(const std::string& payload)
+ template<>
+ void get_payload_array::copy_to_array(const std::string& item, void* array, size_t pos)
+ {
+ ((char**)array)[pos] = OICStrdup(item.c_str());
+ }
+
+ template<>
+ void get_payload_array::copy_to_array(OC::OCRepresentation item, void* array, size_t pos)
+ {
+ ((OCRepPayload**)array)[pos] = item.getPayload();
+ }
+
+ void OCRepresentation::getPayloadArray(OCRepPayload* payload,
+ const OCRepresentation::AttributeItem& item) const
{
- std::stringstream os(payload);
+ get_payload_array vis{};
+ boost::apply_visitor(vis, m_values[item.attrname()]);
+
+
+ switch(item.base_type())
{
- InputArchiveType archive(os);
- archive(cereal::make_nvp(OC::Key::OCKEY, m_reps));
+ case AttributeType::Integer:
+ OCRepPayloadSetIntArrayAsOwner(payload, item.attrname().c_str(),
+ (int64_t*)vis.array,
+ vis.dimensions);
+ break;
+ case AttributeType::Double:
+ OCRepPayloadSetDoubleArrayAsOwner(payload, item.attrname().c_str(),
+ (double*)vis.array,
+ vis.dimensions);
+ break;
+ case AttributeType::Boolean:
+ OCRepPayloadSetBoolArrayAsOwner(payload, item.attrname().c_str(),
+ (bool*)vis.array,
+ vis.dimensions);
+ break;
+ case AttributeType::String:
+ OCRepPayloadSetStringArrayAsOwner(payload, item.attrname().c_str(),
+ (char**)vis.array,
+ vis.dimensions);
+ break;
+ case AttributeType::OCRepresentation:
+ OCRepPayloadSetPropObjectArrayAsOwner(payload, item.attrname().c_str(),
+ (OCRepPayload**)vis.array, vis.dimensions);
+ break;
+ default:
+ throw std::logic_error(std::string("GetPayloadArray: Not Implemented") +
+ std::to_string((int)item.base_type()));
}
}
- void MessageContainer::setJSONRepresentation(const char* payload)
+ OCRepPayload* OCRepresentation::getPayload() const
{
- setJSONRepresentation(std::string(payload));
+ OCRepPayload* root = OCRepPayloadCreate();
+ if(!root)
+ {
+ throw std::bad_alloc();
+ }
+
+ OCRepPayloadSetUri(root, getUri().c_str());
+
+ for(const std::string& type : getResourceTypes())
+ {
+ OCRepPayloadAddResourceType(root, type.c_str());
+ }
+
+ for(const std::string& iface : getResourceInterfaces())
+ {
+ OCRepPayloadAddInterface(root, iface.c_str());
+ }
+
+ for(auto& val : *this)
+ {
+ switch(val.type())
+ {
+ case AttributeType::Null:
+ OCRepPayloadSetNull(root, val.attrname().c_str());
+ break;
+ case AttributeType::Integer:
+ OCRepPayloadSetPropInt(root, val.attrname().c_str(), static_cast<int>(val));
+ break;
+ case AttributeType::Double:
+ OCRepPayloadSetPropDouble(root, val.attrname().c_str(), val);
+ break;
+ case AttributeType::Boolean:
+ OCRepPayloadSetPropBool(root, val.attrname().c_str(), val);
+ break;
+ case AttributeType::String:
+ OCRepPayloadSetPropString(root, val.attrname().c_str(),
+ static_cast<std::string>(val).c_str());
+ break;
+ case AttributeType::OCRepresentation:
+ OCRepPayloadSetPropObjectAsOwner(root, val.attrname().c_str(),
+ static_cast<OCRepresentation>(val).getPayload());
+ break;
+ case AttributeType::Vector:
+ getPayloadArray(root, val);
+ break;
+ default:
+ throw std::logic_error(std::string("Getpayload: Not Implemented") +
+ std::to_string((int)val.type()));
+ break;
+ }
+ }
+
+ OCRepPayload* cur = root;
+ for(auto& child : this->getChildren())
+ {
+ cur->next = child.getPayload();
+ cur = cur->next;
+ }
+
+ return root;
}
- std::string MessageContainer::getJSONRepresentation(OCInfoFormat f) const
+ size_t calcArrayDepth(const size_t dimensions[MAX_REP_ARRAY_DEPTH])
{
- std::stringstream os;
+ if(dimensions[0] == 0)
+ {
+ throw std::logic_error("invalid calcArrayDepth");
+ }
+ else if(dimensions[1] == 0)
+ {
+ return 1;
+ }
+ else if (dimensions[2] == 0)
+ {
+ return 2;
+ }
+ else
+ {
+ return 3;
+ }
+ }
+
+ template<typename T>
+ T OCRepresentation::payload_array_helper_copy(size_t index, const OCRepPayloadValue* pl)
+ {
+ throw std::logic_error("payload_array_helper_copy: unsupported type");
+ }
+ template<>
+ int OCRepresentation::payload_array_helper_copy<int>(size_t index, const OCRepPayloadValue* pl)
+ {
+ return pl->arr.iArray[index];
+ }
+ template<>
+ double OCRepresentation::payload_array_helper_copy<double>(size_t index, const OCRepPayloadValue* pl)
+ {
+ return pl->arr.dArray[index];
+ }
+ template<>
+ bool OCRepresentation::payload_array_helper_copy<bool>(size_t index, const OCRepPayloadValue* pl)
+ {
+ return pl->arr.bArray[index];
+ }
+ template<>
+ std::string OCRepresentation::payload_array_helper_copy<std::string>(
+ size_t index, const OCRepPayloadValue* pl)
+ {
+ return std::string(pl->arr.strArray[index]);
+ }
+ template<>
+ OCRepresentation OCRepresentation::payload_array_helper_copy<OCRepresentation>(
+ size_t index, const OCRepPayloadValue* pl)
+ {
+ OCRepresentation r;
+ r.setPayload(pl->arr.objArray[index]);
+ return r;
+ }
- // note: the block is required because cereal closes the JSON string
- // upon destruction, so the archive needs to be destroyed before accessing
- // the data
+ template<typename T>
+ void OCRepresentation::payload_array_helper(const OCRepPayloadValue* pl, size_t depth)
+ {
+ if(depth == 1)
{
- if(f == OCInfoFormat::IncludeOC)
+ std::vector<T> val(pl->arr.dimensions[0]);
+
+ for(size_t i = 0; i < pl->arr.dimensions[0]; ++i)
{
- OutputArchiveType archive(os);
- archive(cereal::make_nvp(OC::Key::OCKEY, m_reps));
+ val[i] = payload_array_helper_copy<T>(i, pl);
}
- else if(f== OCInfoFormat::ExcludeOC)
+ this->setValue(std::string(pl->name), val);
+ }
+ else if (depth == 2)
+ {
+ std::vector<std::vector<T>> val(pl->arr.dimensions[0]);
+ for(size_t i = 0; i < pl->arr.dimensions[0]; ++i)
{
- bool firstPrinted = false;
- for(std::vector<OCRepresentation>::size_type i = 0; i< m_reps.size();++i)
+ val[i].reserve(pl->arr.dimensions[1]);
+ for(size_t j = 0; j < pl->arr.dimensions[1]; ++j)
{
- if(!m_reps[i].emptyData())
+ val[i][j] = payload_array_helper_copy<T>(
+ i * pl->arr.dimensions[1] + j, pl);
+ }
+ }
+ this->setValue(std::string(pl->name), val);
+ }
+ else if (depth == 3)
+ {
+ std::vector<std::vector<std::vector<T>>> val;
+ for(size_t i = 0; i < pl->arr.dimensions[0]; ++i)
+ {
+ val[i].reserve(pl->arr.dimensions[1]);
+ for(size_t j = 0; j < pl->arr.dimensions[1]; ++j)
+ {
+ val[i][j].reserve(pl->arr.dimensions[2]);
+ for(size_t k = 0; k < pl->arr.dimensions[2]; ++k)
{
- if(firstPrinted)
- {
- os<<',';
- }
- firstPrinted=true;
- os << m_reps[i].getJSONRepresentation();
+ val[i][j][k] = payload_array_helper_copy<T>(
+ pl->arr.dimensions[2] * j +
+ pl->arr.dimensions[2] * pl->arr.dimensions[1] * i +
+ k,
+ pl);
}
}
}
+ this->setValue(std::string(pl->name), val);
+ }
+ else
+ {
+ throw std::logic_error("Invalid depth in payload_array_helper");
}
- return os.str();
}
- const std::vector<OCRepresentation>& MessageContainer::representations() const
+ void OCRepresentation::setPayloadArray(const OCRepPayloadValue* pl)
{
- return m_reps;
- }
- void MessageContainer::addRepresentation(const OCRepresentation& rep)
- {
- m_reps.push_back(rep);
+ switch(pl->arr.type)
+ {
+ case OCREP_PROP_INT:
+ payload_array_helper<int>(pl, calcArrayDepth(pl->arr.dimensions));
+ break;
+ case OCREP_PROP_DOUBLE:
+ payload_array_helper<double>(pl, calcArrayDepth(pl->arr.dimensions));
+ break;
+ case OCREP_PROP_BOOL:
+ payload_array_helper<bool>(pl, calcArrayDepth(pl->arr.dimensions));
+ break;
+ case OCREP_PROP_STRING:
+ payload_array_helper<std::string>(pl, calcArrayDepth(pl->arr.dimensions));
+ break;
+ case OCREP_PROP_OBJECT:
+ payload_array_helper<OCRepresentation>(pl, calcArrayDepth(pl->arr.dimensions));
+ break;
+ default:
+ throw std::logic_error("setPayload array invalid type");
+ break;
+ }
}
-}
-namespace OC
-{
- std::string OCRepresentation::getJSONRepresentation() const
+ void OCRepresentation::setPayload(const OCRepPayload* pl)
{
- if(emptyData())
+ setUri(pl->uri);
+
+ OCStringLL* ll = pl->types;
+ while(ll)
{
- return "{}";
+ addResourceType(ll->value);
+ ll = ll->next;
}
- std::stringstream os;
-
- // note: the block is required because cereal closes the JSON string
- // upon destruction, so the archive needs to be destroyed before accessing
- // the data
+ ll = pl->interfaces;
+ while(ll)
{
- OutputArchiveType archive (os);
- save(archive);
+ addResourceInterface(ll->value);
+ ll = ll->next;
}
- return os.str();
+ OCRepPayloadValue* val = pl->values;
+
+ while(val)
+ {
+ switch(val->type)
+ {
+ case OCREP_PROP_NULL:
+ setNULL(val->name);
+ break;
+ case OCREP_PROP_INT:
+ setValue<int>(val->name, val->i);
+ break;
+ case OCREP_PROP_DOUBLE:
+ setValue<double>(val->name, val->d);
+ break;
+ case OCREP_PROP_BOOL:
+ setValue<bool>(val->name, val->b);
+ break;
+ case OCREP_PROP_STRING:
+ setValue<std::string>(val->name, val->str);
+ break;
+ case OCREP_PROP_OBJECT:
+ {
+ OCRepresentation cur;
+ cur.setPayload(val->obj);
+ setValue<OCRepresentation>(val->name, cur);
+ }
+ break;
+ case OCREP_PROP_ARRAY:
+ setPayloadArray(val);
+ break;
+ default:
+ throw std::logic_error(std::string("Not Implemented!") +
+ std::to_string((int)val->type));
+ break;
+ }
+ val = val->next;
+ }
}
void OCRepresentation::addChild(const OCRepresentation& rep)
m_resourceTypes = resourceTypes;
}
+ void OCRepresentation::addResourceType(const std::string& str)
+ {
+ m_resourceTypes.push_back(str);
+ }
+
const std::vector<std::string>& OCRepresentation::getResourceInterfaces() const
{
return m_interfaces;
}
+ void OCRepresentation::addResourceInterface(const std::string& str)
+ {
+ m_interfaces.push_back(str);
+ }
+
void OCRepresentation::setResourceInterfaces(const std::vector<std::string>& resourceInterfaces)
{
m_interfaces = resourceInterfaces;
namespace OC
{
- template <class Archive, class Val>
- void OCRepresentation::optional_load(Archive& ar, Val&& v)
- {
- try
- {
- ar(v);
- }
- catch(cereal::Exception&)
- {
- ar.setNextName(nullptr);
- // Loading a key that doesn't exist results in an exception
- // Since "Not Found" is a valid condition for us, we swallow
- // this exception and the archive will not load anything
- }
- }
-
- template<class Archive>
- void OCRepresentation::save(Archive& ar) const
- {
- // printed for all interface types
- if(!m_uri.empty())
- {
- ar(cereal::make_nvp(Key::URIKEY, m_uri));
- }
-
- if((m_interfaceType == InterfaceType::None
- || m_interfaceType==InterfaceType::DefaultChild
- || m_interfaceType==InterfaceType::LinkChild)
- && (m_resourceTypes.size()>0 || m_interfaces.size()>0))
- {
- // The Prop object requires that it refer to non-const vectors
- // so that it can alter them in the 'load' case. In the save case
- // (initiated here) it will not modify the object. So, to keep the
- // compiler happy, removing the 'const' context here is necessary.
- const std::vector<std::string>& rt(m_resourceTypes);
- const std::vector<std::string>& intf(m_interfaces);
- Prop temp(const_cast<std::vector<std::string>&>(rt),
- const_cast<std::vector<std::string>&>(intf));
- ar(cereal::make_nvp(Key::PROPERTYKEY, temp));
- }
-
- // printed only for BatchChildren and DefaultParent
- if((m_interfaceType == InterfaceType::None
- || m_interfaceType == InterfaceType::BatchChild
- || m_interfaceType == InterfaceType::DefaultParent)
- && m_values.size()>0)
- {
- ar(cereal::make_nvp(Key::REPKEY, m_values));
- }
- }
-
- template<class Archive>
- void OCRepresentation::load(Archive& ar)
- {
- optional_load(ar, cereal::make_nvp(Key::URIKEY, m_uri));
- {
- Prop temp(m_resourceTypes, m_interfaces);
- optional_load(ar, cereal::make_nvp(Key::PROPERTYKEY, temp));
- }
- optional_load(ar, cereal::make_nvp(Key::REPKEY, m_values));
- }
-
- template<class Archive>
- void OCRepresentation::Prop::save(Archive& ar) const
- {
- if(m_types.size() > 0)
- {
- ar(cereal::make_nvp(Key::RESOURCETYPESKEY, m_types));
- }
-
- if(m_interfaces.size()>0)
- {
- ar(cereal::make_nvp(Key::INTERFACESKEY, m_interfaces));
- }
- }
-
- template<class Archive>
- void OCRepresentation::Prop::load(Archive& ar)
- {
- optional_load(ar, cereal::make_nvp(Key::RESOURCETYPESKEY, m_types));
- optional_load(ar, cereal::make_nvp(Key::INTERFACESKEY, m_interfaces));
- }
-}
-
-// note: the below is used to load an AttributeValue map out of JSON
-namespace OC
-{
- namespace detail
- {
- enum class typeTag:uint8_t
- {
- NOTHING = 0,
- _string,
- _int,
- _double,
- _bool,
- _representation
- };
-
- typedef rapidjson::Document::GenericValue GenericValue;
-
- AttributeValue parseAttributeValue(const GenericValue& v);
- AttributeValue parseAttributeValue(const GenericValue& v,
- const unsigned int curLevel, unsigned int& maxDepth, typeTag& t);
- AttributeValue parseAttributeValueObject(const GenericValue& v, typeTag& t);
- AttributeValue parseAttributeValueArray(const GenericValue& v,
- const unsigned int curLevel, unsigned int& maxDepth, typeTag& t);
- AttributeValue parseAttributeValuePrimitive(const GenericValue& v, typeTag& t);
-
- AttributeValue parseAttributeValue(const GenericValue& v)
- {
- // base entrance, start everything at '0'
- unsigned int max_depth {0};
- typeTag t {typeTag::NOTHING};
-
- return parseAttributeValue(v, 0, max_depth, t);
- }
-
- AttributeValue parseAttributeValue(const GenericValue& v,
- const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
- {
- if(v.IsObject())
- {
- return parseAttributeValueObject(v, t);
- }
- else if(v.IsArray())
- {
- return parseAttributeValueArray(v, curLevel + 1, maxDepth, t);
- }
- else
- {
- return parseAttributeValuePrimitive(v,t);
- }
- }
-
- AttributeValue parseAttributeValueObject(const GenericValue& v, typeTag& t)
- {
- typedef rapidjson::Value::ConstMemberIterator CMI;
- t = typeTag::_representation;
- OC::OCRepresentation rep;
-
- for(CMI itr = v.MemberBegin(); itr!= v.MemberEnd(); ++itr)
- {
- std::string keyName = itr->name.GetString();
-
- if(keyName == OC::Key::URIKEY)
- {
- rep.setUri(boost::get<std::string>(parseAttributeValue(itr->value)));
- }
- else if (keyName == OC::Key::PROPERTYKEY)
- {
- for(CMI itr2 = itr->value.MemberBegin();
- itr->value.MemberEnd()!=itr2;
- ++itr2)
- {
- if(keyName == OC::Key::RESOURCETYPESKEY)
- {
- rep.setResourceTypes(
- boost::get<std::vector<std::string>>(
- parseAttributeValue(itr->value)));
- }
- else if(keyName == OC::Key::INTERFACESKEY)
- {
- rep.setResourceInterfaces(
- boost::get<std::vector<std::string>>(
- parseAttributeValue(itr->value)));
- }
- }
- }
- else if (keyName == OC::Key::REPKEY)
- {
- for(CMI itr2 = itr->value.MemberBegin();
- itr->value.MemberEnd()!=itr2;
- ++itr2)
- {
- rep.setValue(itr2->name.GetString(),
- parseAttributeValue(itr2->value));
- }
- }
- }
-
- return rep;
- }
-
- AttributeValue parseAttributeValuePrimitive(const GenericValue& v, typeTag& t)
- {
- if(v.IsString())
- {
- t = typeTag::_string;
- return std::string(v.GetString());
- }
- else if (v.IsNumber())
- {
- if(v.IsDouble())
- {
- t = typeTag::_double;
- return double(v.GetDouble());
- }
- else if (v.IsInt())
- {
- t = typeTag::_int;
- return int(v.GetInt());
- }
- else
- {
- throw OC::OCException(OC::Exception::INVALID_JSON_NUMERIC
- + std::to_string(v.GetType()));
- }
- }
- else if(v.IsBool_())
- {
- t=typeTag::_bool;
- return bool(v.GetBool_());
- }
- else if(v.IsNull_())
- {
- return OC::NullType();
- }
- else
- {
- throw OC::OCException(OC::Exception::INVALID_JSON_TYPE
- + std::to_string(v.GetType()));
- }
- }
-
- std::vector<AttributeValue> gatherArrayContents(const GenericValue& v,
- const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
- {
- std::vector<AttributeValue> out;
-
- std::transform(v.Begin(), v.End(), back_inserter(out),
- [curLevel, &maxDepth, &t](const GenericValue& x)
- {
- return parseAttributeValue(x, curLevel, maxDepth, t);
- });
- return out;
- }
-
- template<class OutT>
- struct valueToConcrete
- {
- OutT operator()(const AttributeValue& v)
- {
- return boost::get<OutT>(v);
- }
-
- };
-
- template <class OutSeqT>
- OutSeqT valuesToConcreteVectors(const std::vector<AttributeValue>& vs)
- {
- OutSeqT ret;
-
- std::transform(begin(vs),end(vs), back_inserter(ret),
- valueToConcrete<typename OutSeqT::value_type>());
- return ret;
- }
-
- template<class valueType>
- AttributeValue remapArrayDepth(const unsigned int curLevel,
- const std::vector<OC::AttributeValue>& vs)
- {
- switch(curLevel)
- {
- default:
- throw OC::OCException(OC::Exception::INVALID_JSON_ARRAY_DEPTH);
- break;
- case 1:
- return valuesToConcreteVectors<std::vector<valueType>>(vs);
- break;
- case 2:
- return valuesToConcreteVectors<std::vector<std::vector<valueType>>>(vs);
- break;
- case 3:
- return valuesToConcreteVectors
- <std::vector<std::vector<std::vector<valueType>>>>(vs);
- break;
- }
- }
-
- AttributeValue convertArrayToConcretes(const typeTag t,
- const unsigned int curLevel, const std::vector<OC::AttributeValue>& vs)
- {
- // This function converts a std::vector of AttributeValue to a std::vector
- // of concrete types. Since we don't use a recursive Variant, we need
- // to get back to a 'base' primitive type
- switch(t)
- {
- default:
- case typeTag::NOTHING:
- throw OC::OCException(OC::Exception::INVALID_JSON_TYPE_TAG);
- break;
- case typeTag::_string:
- return remapArrayDepth<std::string>(curLevel, vs);
- break;
- case typeTag::_int:
- return remapArrayDepth<int>(curLevel, vs);
- break;
- case typeTag::_double:
- return remapArrayDepth<double>(curLevel, vs);
- break;
- case typeTag::_bool:
- return remapArrayDepth<bool>(curLevel, vs);
- break;
- case typeTag::_representation:
- return remapArrayDepth<OCRepresentation>(curLevel, vs);
- break;
- }
- }
-
- AttributeValue parseAttributeValueArray(const GenericValue& v,
- const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
- {
- const unsigned int max_level = 3;
-
- if(curLevel > max_level)
- {
- throw OC::OCException(OC::Exception::INVALID_JSON_ARRAY_DEPTH);
- }
-
- if(curLevel > maxDepth)
- {
- maxDepth = curLevel;
- }
-
- auto arrayItems = gatherArrayContents(v, curLevel, maxDepth, t);
- const int remapLevel = maxDepth - (curLevel -1);
- return convertArrayToConcretes(t, remapLevel, arrayItems);
- }
- }
-}
-
-namespace cereal
-{
- void JSONInputArchive::loadAttributeValues(std::map<std::string, OC::AttributeValue>& map)
- {
- for(auto&b = itsIteratorStack.back();
- b.Member && b.itsMemberItEnd != b.itsMemberItBegin+b.itsIndex;
- ++b)
- {
- std::string key = b.itsMemberItBegin[b.itsIndex].name.GetString();
- const GenericValue& v = itsIteratorStack.back().value();
- map[key] = OC::detail::parseAttributeValue(v);
- }
- }
-}
-
-namespace OC
-{
std::ostream& operator <<(std::ostream& os, const AttributeType at)
{
switch(at)
#include "OCUtilities.h"
#include <boost/lexical_cast.hpp>
+#include <sstream>
namespace OC {
+static const char COAP[] = "coap://";
+static const char COAPS[] = "coaps://";
using OC::nil_guard;
using OC::result_guard;
using OC::checked_guard;
{
throw std::length_error("host address is too long.");
}
- host.copy(m_devAddr.addr, len);
- m_devAddr.addr[len] = '\0';
+
+ this->setHost(host);
}
OCResource::~OCResource()
{
}
+void OCResource::setHost(const std::string& host)
+{
+ size_t prefix_len;
+
+ if(host.compare(0, sizeof(COAP) - 1, COAP) == 0)
+ {
+ prefix_len = sizeof(COAP) - 1;
+ }
+ else if(host.compare(0, sizeof(COAPS) - 1, COAPS) == 0)
+ {
+ prefix_len = sizeof(COAPS) - 1;
+ m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags & OC_SECURE);
+ }
+ else
+ {
+ throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+ m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+ }
+
+ // removed coap:// or coaps://
+ std::string host_token = host.substr(prefix_len);
+
+ if(host_token[0] == '[')
+ {
+ m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags & OC_IP_USE_V6);
+
+ size_t found = host_token.find(']');
+
+ if(found == std::string::npos)
+ {
+ throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+ m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+ }
+ // extract the ipaddress
+ std::string ip6Addr = host_token.substr(1, found-1);
+ ip6Addr.copy(m_devAddr.addr, sizeof(m_devAddr.addr));
+ m_devAddr.addr[ip6Addr.length()] = '\0';
+ //skip ']' and ':' characters in host string
+ host_token = host_token.substr(found + 2);
+ }
+ else
+ {
+ size_t found = host_token.find(':');
+
+ if(found == std::string::npos)
+ {
+ throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+ m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+ }
+
+ std::string addrPart = host_token.substr(0, found);
+ addrPart.copy(m_devAddr.addr, sizeof(m_devAddr.addr));
+ m_devAddr.addr[addrPart.length()] = '\0';
+ //skip ':' character in host string
+ host_token = host_token.substr(found + 1);
+ }
+
+ int port = std::stoi(host_token);
+
+ if( port < 0 || port > UINT16_MAX )
+ {
+ throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
+ m_interfaces.empty(), m_clientWrapper.expired(), false, false);
+ }
+
+ m_devAddr.port = static_cast<uint16_t>(port);
+
+}
+
OCStackResult OCResource::get(const QueryParamsMap& queryParametersMap,
GetCallback attributeHandler, QualityOfService QoS)
{
std::string OCResource::host() const
{
- return std::string(m_devAddr.addr);
+ std::ostringstream ss;
+ if (m_devAddr.flags & OC_SECURE)
+ {
+ ss << COAPS;
+ }
+ else
+ {
+ ss << COAP;
+ }
+ if (m_devAddr.flags & OC_IP_USE_V6)
+ {
+ ss << '[' << m_devAddr.addr << ']';
+ }
+ else
+ {
+ ss << m_devAddr.addr;
+ }
+ if (m_devAddr.port)
+ {
+ ss << ':' << m_devAddr.port;
+ }
+ return ss.str();
}
std::string OCResource::uri() const
#include <vector>
#include <map>
-#include <cereal/cereal.hpp>
-#include <OicJsonSerializer.hpp>
+#include "ocpayload.h"
using namespace OC;
-using namespace std;
-void OCResourceRequest::setPayload(const std::string& requestPayload)
+void OCResourceRequest::setPayload(OCPayload* payload)
{
MessageContainer info;
- if(requestPayload.empty())
+ if(payload == nullptr || payload->type != PAYLOAD_TYPE_REPRESENTATION)
{
+ throw std::logic_error("Wrong payload type");
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;
- }
+ info.setPayload(payload);
const std::vector<OCRepresentation>& reps = info.representations();
if(reps.size() >0)
'OCResourceRequest.cpp'
]
-oclib_env.AppendUnique(CPPPATH = [oclib_env.get('SRC_DIR') + '/extlibs/cereal/include'])
oclib = oclib_env.SharedLibrary('oc', oclib_src)
oclib_env.InstallTarget(oclib, 'liboc')
+oclib_env.UserInstallTargetLib(oclib, 'liboc')
TEST(FindResourceTest, DISABLED_FindResourceValid)
{
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK, OCPlatform::findResource("", requestURI.str(),
CT_DEFAULT, &foundResource));
}
TEST(FindResourceTest, FindResourceNullResourceURI1)
{
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
EXPECT_ANY_THROW(OCPlatform::findResource(nullptr, requestURI.str(),
CT_DEFAULT, &foundResource));
}
TEST(FindResourceTest, FindResourceNullHost)
{
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
EXPECT_ANY_THROW(OCPlatform::findResource(nullptr, requestURI.str(),
CT_DEFAULT, &foundResource));
}
TEST(FindResourceTest, FindResourceNullresourceHandler)
{
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
EXPECT_THROW(OCPlatform::findResource("", requestURI.str(),
CT_DEFAULT, NULL), OC::OCException);
}
TEST(FindResourceTest, DISABLED_FindResourceWithLowQoS)
{
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK,
OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource,
OC::QualityOfService::LowQos));
TEST(FindResourceTest, DISABLED_FindResourceWithMidQos)
{
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK,
OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource,
OC::QualityOfService::MidQos));
TEST(FindResourceTest, DISABLED_FindResourceWithHighQos)
{
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK,
OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource,
OC::QualityOfService::HighQos));
TEST(FindResourceTest, DISABLED_FindResourceWithNaQos)
{
std::ostringstream requestURI;
- requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK,
OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource,
OC::QualityOfService::NaQos));
<?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="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>
--- /dev/null
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="org.iotivity.ResourceHosting"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk
+ android:minSdkVersion="8"
+ android:targetSdkVersion="21" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ </application>
+
+</manifest>
--- /dev/null
+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 := ca_i
+LOCAL_SRC_FILES := ../libs/libca-interface.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 := ocstack-jni
+LOCAL_SRC_FILES := ../libs/libocstack-jni.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := NotificationManager
+LOCAL_SRC_FILES := ../libs/libNotificationManager.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := ResourceHosing_JNI
+LOCAL_CPPFLAGS := -std=c++0x -frtti -fexceptions
+
+LOCAL_STATIC_LIBRARIES = ca_i
+LOCAL_STATIC_LIBRARIES += ca
+LOCAL_STATIC_LIBRARIES += oc_logger_core
+LOCAL_STATIC_LIBRARIES += oc_logger
+LOCAL_STATIC_LIBRARIES += octbstack
+LOCAL_STATIC_LIBRARIES += oc
+LOCAL_STATIC_LIBRARIES += ocstack-jni
+LOCAL_STATIC_LIBRARIES += NotificationManager
+
+LOCAL_C_INCLUDES := ../../../../../../resource/csdk/stack/include/
+LOCAL_C_INCLUDES += ../../../../../../resource/csdk/logger/include/
+LOCAL_C_INCLUDES += ../../../../../../resource/include/
+LOCAL_C_INCLUDES += ../../../../../../resource/oc_logger/include/
+LOCAL_C_INCLUDES += ../../../../../../extlibs/boost/boost_1_58_0/
+LOCAL_C_INCLUDES += ../../../../NotificationManager/include/
+
+
+LOCAL_SRC_FILES := ResourceHosing_JNI.cpp
+include $(BUILD_SHARED_LIBRARY)
+
//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
extern "C" {
#include "hosting.h"
}
-#include "resourceCoordinator_JNI.h"
-#include "android_cpp11_compat.h"
+#include "ResourceHosing_JNI.h"
+#include "OCAndroid.h"
using namespace std;
if (OCProcess() != OC_STACK_OK)
{
- //OCProcess ERROR
+ return ;
}
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
+JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_OICCoordinatorStart
(JNIEnv *env, jobject obj)
{
jint result = 0;
if(threadRun==true)
{
-
- messageCallback(env,obj,"OICCoordinatorStart already executed");
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
+JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_OICCoordinatorStop
(JNIEnv *env, jobject obj)
{
- messageCallback(env,obj,"OICCoordinatorStop");
jint result = 0;
//terminate Thread
if (ocProcessThread.joinable())
}
else
{
- messageCallback(env,obj,"OICCoordinatorStop already terminated");
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
+JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_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)
if(OCInit(addr,USE_RANDOM_PORT,OC_CLIENT_SERVER)!=OC_STACK_OK)
{
- messageCallback(env,obj,"OCStack init Error");
return (jint)OCSTACK_ERROR;
}
return (jint)OCSTACK_OK;
}
-JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingTerminate
+JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_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
}
else
{
- messageCallback(env,obj,"The thread may be not running.");
return (jint)HOSTING_THREAD_ERROR;
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#ifndef RESOURCECOORDINATOR_JNI_H_
-#define RESOURCECOORDINATOR_JNI_H_
+#ifndef RESOURCEHOSTING_JNI_H_
+#define RESOURCEHOSTING_JNI_H_
#include <jni.h>
#include <thread>
#endif
/*
- * Class: org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Class: org_iotivity_service_resourcehosting_ResourceHosting
* Method: OICCoordinatorStart
* Signature: ()V
*/
-JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStart
+JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_OICCoordinatorStart
(JNIEnv *, jobject);
/*
- * @Class: org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * @Class: org_iotivity_service_resourcehosting_ResourceHosting
* @Method: OICCoordinatorStop
* @Signature: ()V
*/
-JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStop
+JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_OICCoordinatorStop
(JNIEnv *, jobject);
/*
- * Class: org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Class: org_iotivity_service_resourcehosting_ResourceHosting
* Method: ResourceHostingInit
* Signature: ()V
*/
-JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingInit
+JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_ResourceHostingInit
(JNIEnv *env, jobject obj,jstring j_addr);
/*
- * Class: org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Class: org_iotivity_service_resourcehosting_ResourceHosting
* Method: ResourceHostingTerminate
* Signature: (Ljava/lang/String;)V
*/
-JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingTerminate
+JNIEXPORT jint JNICALL Java_org_iotivity_ResourceHosting_ResourceHosting_ResourceHostingTerminate
(JNIEnv *env, jobject obj);
#ifdef __cplusplus
}
#endif
-#endif /* RESOURCECOORDINATOR_JNI_H_ */
+#endif /* RESOURCEHOSTING_JNI_H_ */
--- /dev/null
+# 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
--- /dev/null
+//******************************************************************
+//
+// 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 org.iotivity.ResourceHosting;
+import java.lang.System;
+import java.lang.String;;
+/**
+ * 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 {
+
+ /**
+ * jni function - OicCorrdinatorstart() method.
+ *
+ * @see Class class :
+ * org_iotivity_resourcehosting_ResourceHosting</br>
+ * @see Method method : OICCoordinatorStart</br>
+ * @see Signature signature : ()V</br>
+ */
+ public native int OICCoordinatorStart();
+
+ /**
+ * jni function - OICCoordinatorStop() method.
+ *
+ * @see Class class :
+ * org_iotivity_resourcehosting_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 :
+ * org_iotivity_resourcehosting_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 :
+ * org_iotivity_resourcehosting_ResourceHosting</br>
+ * @see Method method : ResourceHostingTerminate</br>
+ * @see signature signature : ()V</br>
+ */
+ public native int ResourceHostingTerminate();
+
+ static {
+ System.loadLibrary("connectivity_abstraction");
+ System.loadLibrary("ca-interface");
+ System.loadLibrary("oc_logger_core");
+ System.loadLibrary("oc_logger");
+ System.loadLibrary("octbstack");
+ System.loadLibrary("oc");
+ System.loadLibrary("ocstack-jni");
+ System.loadLibrary("NotificationManager");
+ System.loadLibrary("ResourceHosing_JNI");
+ }
+}
cbData.cd = NULL;
char queryUri[OIC_STRING_MAX_VALUE] = { '\0' };
- snprintf(queryUri, sizeof(queryUri), "coap://%s%s", sourceResourceAddress , OC_PRESENCE_URI);
+ snprintf(queryUri, sizeof(queryUri), "coap://%s%s", sourceResourceAddress , OC_RSRVD_PRESENCE_URI);
OC_LOG_V(DEBUG, HOSTING_TAG, "initializePresenceForCoordinating Query : %s", queryUri);
result = OCDoResource(&handle, OC_REST_PRESENCE, queryUri, 0, 0,
{
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 @ %s:%d",
- clientResponse->resJSONPayload,
- clientResponse->devAddr.addr,
- clientResponse->devAddr.port);
+ //OC_LOG_V(DEBUG, HOSTING_TAG,
+ // "\tPresence Device =============> Presence %s @ %s:%d",
+ // clientResponse->resJSONPayload,
+ // clientResponse->devAddr.addr,
+ // clientResponse->devAddr.port);
snprintf(address, sizeof(address), "%s:%d",
clientResponse->devAddr.addr,
{
cJSON *discoveryJson = cJSON_CreateObject();
- discoveryJson = cJSON_Parse((char *)clientResponse->resJSONPayload);
+ //discoveryJson = cJSON_Parse((char *)clientResponse->resJSONPayload);
cJSON *ocArray = cJSON_GetObjectItem(discoveryJson, "oc");
char *ocArray_str = cJSON_PrintUnformatted(ocArray);
clientResponse->devAddr.addr,
clientResponse->devAddr.port);
- OC_LOG_V(DEBUG, HOSTING_TAG, "Host Device =============> Discovered %s @ %s",
- clientResponse->resJSONPayload, sourceaddr);
+ //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)
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);
+ //OC_LOG_V(DEBUG, HOSTING_TAG, "JSON = %s =============> Obs Response",
+ // clientResponse->resJSONPayload);
- MirrorResource *foundMirrorResource = updateMirrorResource(handle, clientResponse->resJSONPayload);
+ MirrorResource *foundMirrorResource = NULL;//updateMirrorResource(handle, clientResponse->resJSONPayload);
if (foundMirrorResource == NULL)
{
OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource : Fail");
mirrorResource->rep = NULL;
}
mirrorResource->rep = cJSON_CreateObject();
- mirrorResource->rep = cJSON_Parse(entityHandlerRequest->reqJSONPayload);
+ //mirrorResource->rep = cJSON_Parse(entityHandlerRequest->reqJSONPayload);
}
OC_LOG_V(DEBUG, HOSTING_TAG, "node's uri : %s", mirrorResource->uri);
entityHandlerResponse.requestHandle = entityHandlerRequest->requestHandle;
entityHandlerResponse.resourceHandle = entityHandlerRequest->resource;
entityHandlerResponse.ehResult = entityHandlerResult;
- entityHandlerResponse.payload = (char *)payload;
- entityHandlerResponse.payloadSize = strlen(payload);
+ //entityHandlerResponse.payload = (char *)payload;
+ //entityHandlerResponse.payloadSize = strlen(payload);
// Indicate that response is NOT in a persistent buffer
entityHandlerResponse.persistentBufferFlag = 0;
if (requestMirrorResourceList->headerNode == NULL)
{
OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found any mirror resource2");
+ destroyMirrorResourceList(requestMirrorResourceList);
return OC_STACK_ERROR;
}
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);
+ //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);
+ //result = OCDoResource(&request->requestHandle[OIC_REQUEST_BY_COORDINATOR],
+ // method, queryFullUri, NULL, payload, OC_TRANSPORT, OC_LOW_QOS, &cbData, NULL, 0);
}
else
{
}
else
{
- OC_LOG_V(DEBUG, HOSTING_TAG, "requestCB's payload: %s", clientResponse->resJSONPayload);
+ //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->method = request->method;
entityHandler->requestHandle = request->entityRequestHandle;
- OCEntityHandlerResponse response = buildEntityHandlerResponse(
- entityHandler, clientResponse->resJSONPayload);
+ OCEntityHandlerResponse response; //= buildEntityHandlerResponse(
+ //entityHandler, clientResponse->resJSONPayload);
if (OCDoResponse(&response) != OC_STACK_OK)
{
OC_LOG_V(DEBUG, HOSTING_TAG, "Error sending response");
cJSON_Delete(observeJson);
- entityHandlerRequest->reqJSONPayload = temp;
+ //entityHandlerRequest->reqJSONPayload = temp;
}
entityHandlerResult = handleRequestPayload(entityHandlerRequest, payload, sizeof(payload) - 1);
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = entityHandlerResult;
- response.payload = (char *)payload;
- response.payloadSize = strlen(payload);
+ //response.payload = (char *)payload;
+ //response.payloadSize = strlen(payload);
// Indicate that response is NOT in a persistent buffer
response.persistentBufferFlag = 0;
NOTI_SRC_DIR + 'requestHandler.c',
NOTI_SRC_DIR + 'virtualResource.c']
-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(notificationsdk, 'libResouceHosting')
+notimgr_env.UserInstallTargetLib(notificationsdk, 'libResouceHosting')
# Go to build sample apps
SConscript('SampleApp/SConscript')
+++ /dev/null
-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)
OcPlatform.OnResourceFoundListener, OnGetListener, OnDeleteListener,
OnObserveListener, OnPutListener
{
- private final String TAG = "sample_consumer";
+ private final String TAG = "NMConsumer : " + this.getClass().getSimpleName();
public static final int OC_STACK_OK = 0;
public static final String OBSERVE = "Observe";
OcPlatform.Configure(cfg);
current_log_result += "Created Platform...\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
findResourceCandidate();
PRINT();
}
nmfindResource("", "/oc/core?rt=Resource.Hosting");
current_log_result += "Finding Resource... \n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
}
public void nmfindResource(String host, String resourceName)
e.printStackTrace();
current_log_result += e.getMessage() + "\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
}
}
{
current_log_result += "Getting Light Representation...\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
}
}
{
current_log_result += "Getting Light Representation...\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
try
{
e.printStackTrace();
current_log_result += e.getMessage() + "\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
}
}
}
Map<String, String> queryParamsMap = new HashMap<String, String>();
current_log_result += "startObserve\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
try
{
e.printStackTrace();
current_log_result += e.getMessage() + "\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
}
}
}
Map<String, String> queryParamsMap = new HashMap<String, String>();
current_log_result += "startGet\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
try
{
e.printStackTrace();
current_log_result += e.getMessage() + "\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
}
}
}
Map<String, String> queryParamsMap = new HashMap<String, String>();
current_log_result += "startPut\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
try
{
e.printStackTrace();
current_log_result += e.getMessage() + "\n";
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
}
}
}
{
case R.id.btn_observe:
tv_select_method_type.setText(OBSERVE);
+ Log.i(TAG, "Method: " + OBSERVE);
startObserve(curResource);
btn_observe.setClickable(false);
break;
case R.id.btn_get:
tv_select_method_type.setText(GET);
+ Log.i(TAG, "Method: " + GET);
startGet(curResource);
btn_get.setClickable(false);
break;
case R.id.btn_put:
tv_select_method_type.setText(PUT);
+ Log.i(TAG, "Method: " + PUT);
startPut(curResource);
btn_put.setClickable(false);
break;
tv_select_method_type.setText(POST);
Toast.makeText(this, "Not Supported Yet", Toast.LENGTH_SHORT)
.show();
+ Log.i(TAG, "Method: " + POST);
break;
case R.id.btn_delete:
tv_select_method_type.setText(DELETE);
+ Log.i(TAG, "Method: " + DELETE);
try {
startDelete(curResource);
} catch (OcException e) {
break;
case R.id.btn_clean:
cleanLogString();
+ Log.i(TAG, "Log textbox is cleared");
break;
default:
if (receive_result != null)
{
tv_receive_result.setText(receive_result);
+ Log.i(TAG, "Received: " + receive_result);
}
if (found_uri != null)
{
tv_found_uri.setText(found_uri);
+ Log.i(TAG, "URI: " + found_uri);
}
if (current_log_result != null)
{
tv_current_log_result.setText(current_log_result);
+ Log.i(TAG, current_log_result);
}
}
final String message = intent
.getStringExtra(MESSAGE);
tv_current_log_result.setText(message);
+ Log.i(TAG, message);
viewText();
}
}
public class SampleProvider extends Activity implements OnClickListener,
IMessageLogger
{
- private final static String TAG = "SampleProvider : ";
+ private final static String TAG = "NMProvider : SampleProvider";
private TextView mLogTextView;
private TextView mTempValue;
private TextView mHumValue;
break;
case R.id.btnLogClear:
mLogTextView.setText("");
+ Log.i(TAG, "Log message cleared");
break;
}
private OcResourceHandle mResourceHandle;
private List<Byte> mObservationIds;
- private static String TAG = "SampleProvider : ";
+ private static String TAG = "NMProvider : TemperatureResource";
TemperatureResource(Context context)
{
{
Log.e(TAG, "go exception");
logMessage(TAG + "RegisterResource error. " + e.getMessage());
- Log.e(TAG, e.getMessage());
+ Log.e(TAG, "RegisterResource error. " + e.getMessage());
}
// logMessage(TAG + "Successfully registered resource");
public void logMessage(String msg)
{
logMsg(msg);
+ Log.i(TAG, msg);
}
public void logMsg(final String text)
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
- android:name="com.example.resourcehostingsampleapp.ResourceHosting"
+ android:name="com.example.resourcehostingsampleapp.ResourceHostingSampleApp"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
package com.example.resourcehostingsampleapp;
+import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
+import org.iotivity.ResourceHosting.ResourceHosting;
import org.iotivity.base.ModeType;
import org.iotivity.base.OcPlatform;
import org.iotivity.base.OcResourceHandle;
*
*/
-public class ResourceHosting extends Activity implements OnClickListener
+public class ResourceHostingSampleApp 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 = "";
+ private ResourceHosting resourceHosting;
/**
* To initialize UI Function Setting.
* @see Class class : com_example_resourcehostingsampleapp_ResourceHosting</br>
findViewById(R.id.btLogClear).setOnClickListener(this);
PlatformConfig platformConfigObj;
-
+ resourceHosting = new ResourceHosting();
platformConfigObj = new PlatformConfig(this,ServiceType.IN_PROC,
ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
protected void onStart()
{
super.onStart();
+ initOICStack();
}
/**
protected void onStop()
{
super.onStop();
+ int result;
+ result = resourceHosting.ResourceHostingTerminate();
+ Log.d(TAG, "ResourceHostingTerminate : "+ result);
}
protected void onResume()
protected void onRestart()
{
super.onRestart();
+ initOICStack();
}
/**
protected void onDestroy()
{
super.onDestroy();
- int result;
- result = OICCoordinatorStop();
- Log.d(TAG, "OICCoordinatorStop() : "+ result);
+ }
+
+ /**
+ * 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 = 0;
+ result = resourceHosting.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;
}
/**
try
{
int result;
- result = OICCoordinatorStart();
+ result = resourceHosting.OICCoordinatorStart();
Log.d(TAG, "OICCoordinatorStart : " + result);
}
catch (Exception e)
break;
case R.id.btnStopHosting:
int result;
- result = OICCoordinatorStop();
+ result = resourceHosting.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");
- }
}
cpluff = cpluff_env.StaticLibrary('cpluff', cpluff_src)
cpluff_env.InstallTarget(cpluff, 'libcpluff')
+cpluff_env.UserInstallTargetLib(cpluff, 'libcpluff')
pmimpl = pmimpl_env.SharedLibrary('pmimpl', pmimpl_src)
plugin_manager_env.InstallTarget([ppm, pmimpl], 'libppm')
+plugin_manager_env.UserInstallTargetLib([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
+ SConscript('src/Android/jni/SConscript')
ppm_jni = ppm_jni_env.SharedLibrary('PluginManager', ppm_jni_src)
ppm_jni_env.InstallTarget(ppm_jni, 'libPluginManager')
+ppm_jni_env.UserInstallTargetLib(ppm_jni, 'libPluginManager')
######################################################################
# Install the libraries to /libs/<TARGET_ARCH> directory
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)
+ ppm_jni_env.Install(ppm_sdk+'/src/Android/libs/'+env.get('TARGET_ARCH'), gnu_lib_path)
break
private static Context m_context;
private static final int TRUE = 1;
private static final int FALSE = 0;
+ private static final String LOG_TAG = "PPMSampleApp : FelixManager";
static final String ANDROID_FRAMEWORK_PACKAGES = ("android,"
+ "android.app,"
}
public static void LogEx(String info) {
- Log.d("felix", info);
+ Log.d(LOG_TAG, info);
}
private FelixManager(Context ctx) {
LogEx("Bundle: " + b.getSymbolicName());
}
} catch (Throwable ex) {
- Log.d("Felix", "could not create framework: " + ex.getMessage(), ex);
+ Log.d(LOG_TAG, "could not create framework: " + ex.getMessage(), ex);
}
}
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()
+ Log.d(LOG_TAG, "bundle: " + b.getBundleId()
+ " symbolicName : " + b.getSymbolicName());
b.uninstall();
- Log.d("Felix", "uninstall end");
+ Log.d(LOG_TAG, "uninstall end");
}
}
} catch (BundleException e) {
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()
+ Log.d(LOG_TAG, "bundle: " + b.getBundleId()
+ " symbolicName : " + b.getSymbolicName());
b.uninstall();
- Log.d("Felix", "uninstall end");
+ Log.d(LOG_TAG, "uninstall end");
}
}
} catch (BundleException e) {
public static int start(String id) {
int flag = TRUE;
- Log.d("Felix", "String id : " + id);
+ Log.d(LOG_TAG, "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());
+ Log.d(LOG_TAG, "symbolicName : " + b.getSymbolicName());
if (b.getSymbolicName().equals(id)) {
- Log.d("Felix", "bundle: " + b.getBundleId()
+ Log.d(LOG_TAG, "bundle: " + b.getBundleId()
+ " symbolicName : " + b.getSymbolicName());
b.start();
- Log.d("Felix", "start end");
+ Log.d(LOG_TAG, "start end");
}
}
} catch (BundleException e) {
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()
+ Log.d(LOG_TAG, "bundle: " + b.getBundleId()
+ " symbolicName : " + b.getSymbolicName());
b.stop();
- Log.d("Felix", "stop end");
+ Log.d(LOG_TAG, "stop end");
}
}
} catch (BundleException e) {
}
public static String getValue(String name, String key) {
- Log.d("FELIX", "getValue");
+ Log.d(LOG_TAG, "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);
+ Log.d(LOG_TAG, "Bundlename: " + bundlename);
if (bundlename.equals(name)) {
if (dic.get("Bundle-" + key) == null) {
- Log.d("FELIX", name + " null");
+ Log.d(LOG_TAG, name + " null");
return "";
}
- Log.d("FELIX", name + " " + dic.get("Bundle-" + key));
+ Log.d(LOG_TAG, name + " " + dic.get("Bundle-" + key));
return dic.get("Bundle-" + key);
}
}
}
public static String getState(String name) {
- Log.d("FELIX", "getState");
+ Log.d(LOG_TAG, "getState");
BundleContext bContext = m_felix.getBundleContext();
org.osgi.framework.Bundle[] bundles = bContext.getBundles();
for (org.osgi.framework.Bundle b : bundles) {
String bundlename = b.getSymbolicName();
if (bundlename.equals(name)) {
- Log.d("FELIX", state_to_string(b.getState()));
+ Log.d(LOG_TAG, state_to_string(b.getState()));
return state_to_string(b.getState());
}
}
- Log.d("FELIX", "null");
+ Log.d(LOG_TAG, "null");
return "";
}
public static int ObservePluginPath(String path) {
int flag = TRUE;
- Log.d("FELIX", "ObservePluginPath" + path);
+ Log.d(LOG_TAG, "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));
+ Log.d(LOG_TAG, "Observing start : " + path);
+ Log.d(LOG_TAG, "Observing event : " + getEventString(event));
}
};
observer.startWatching();
int flag = TRUE;
if (path == "") {
System.out.println("PluginManager path is Null\n");
- Log.d("FELIX", "PluginManager path is Null\n");
+ Log.d(LOG_TAG, "PluginManager path is Null\n");
flag = FALSE;
return flag;
}
} else {
String fullPath = "/data/data/"
+ m_context.getPackageName() + "/" + path;
- Log.d("FELIX", fullPath);
+ Log.d(LOG_TAG, fullPath);
File dir = new File(fullPath);
if (!dir.exists())
}
}
} catch (IOException ex) {
- Log.e("tag", "I/O Exception", ex);
+ Log.e(LOG_TAG, "I/O Exception", ex);
}
}
out.close();
out = null;
} catch (Exception e) {
- Log.e("tag", e.getMessage());
+ Log.e(LOG_TAG, e.getMessage());
}
}
}
\ No newline at end of file
import android.util.Log;
public class FoundResource implements OcPlatform.OnResourceFoundListener {
- final private static String TAG = "FoundResource";
+ final private static String TAG = "PPMSampleApp : FoundResource";
public void onResourceFound(OcResource resource) {
static ToggleButton Hue;
static android.widget.NumberPicker hue_color;
static Activity mActivity;
+ final private static String LOG_TAG = "PPMSampleApp : MainActivity";
PluginManager m_pm;
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) {
OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY,
OcConnectivityType.ALL, foundResource);
} catch (Exception e) {
- Log.e("Felix", "Exception : " + e);
+ Log.e(LOG_TAG, "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");
+ Log.i(LOG_TAG, "Belkin button click listener");
OcRepresentation rep = new OcRepresentation();
try {
if (belkinplug.m_power == null) {
- Log.i("Felix", "m_power is null");
+ Log.i(LOG_TAG, "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");
+ Log.i(LOG_TAG, "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");
+ Log.i(LOG_TAG, "belkin wemo on");
rep.setValue("power", "on");
} else {
rep.setValue("power", "on");
rep.setValue("brightness", 0);
rep.setValue("color", 0);
} catch (OcException e) {
- Log.e("Felix", e.getMessage());
+ Log.e(LOG_TAG, e.getMessage());
}
OnPutBelkinplug onPut = new OnPutBelkinplug();
if (belkinResource != null) {
} else {
Toast.makeText(getApplicationContext(), "Belkinplug null",
Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Belkinplug null");
}
}
});
belkinstart = (Button) findViewById(R.id.Button01);
belkinstart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "start button click listener");
+ Log.i(LOG_TAG, "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!!!");
+ Log.i(LOG_TAG, "run called!!!");
FoundResource foundResource = new FoundResource();
try {
OcPlatform
belkinstop = (Button) findViewById(R.id.Button02);
belkinstop.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "stop button click listener");
+ Log.i(LOG_TAG, "stop button click listener");
m_pm.stopPlugins("ResourceType", "device.smartplug");
belkinResource = null;
try {
belkingetPlugins = (Button) findViewById(R.id.Button03);
belkingetPlugins.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "getPlugins button click listener");
+ Log.i(LOG_TAG, "getPlugins button click listener");
user_plugin = m_pm.getPlugins();
// key = "name";
state = "";
belkingetPlugins = (Button) findViewById(R.id.Button04);
belkingetPlugins.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "getState click listener");
+ Log.i(LOG_TAG, "getState click listener");
state = m_pm.getState("wemo");
if (state == "")
state = "null";
belkinrescan = (Button) findViewById(R.id.Button05);
belkinrescan.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "Rescan Plugin click listener");
+ Log.i(LOG_TAG, "Rescan Plugin click listener");
m_pm.rescanPlugin();
try {
Thread.sleep(2000);
Gear = (Button) findViewById(R.id.btn_gear);
Gear.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "Gear button click listener");
+ Log.i(LOG_TAG, "Gear button click listener");
OcRepresentation rep = new OcRepresentation();
try{
rep.setValue("brightness", 0);
rep.setValue("color", 0);
} catch (OcException e) {
- Log.e("Felix", e.getMessage());
+ Log.e(LOG_TAG, e.getMessage());
}
if (gearResource != null) {
Toast.makeText(getApplicationContext(),
"Send Noti. to Gear", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Send Noti. to Gear");
try {
OnPutGear onPut = new OnPutGear();
gearResource.put(rep, new HashMap<String, String>(),
} else {
Toast.makeText(getApplicationContext(), "Gear is null",
Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Gear is null");
}
}
});
gearstart = (Button) findViewById(R.id.Button06);
gearstart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "start button click listener");
+ Log.i(LOG_TAG, "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!!!");
+ Log.i(LOG_TAG, "run called!!!");
FoundResource foundResource = new FoundResource();
try {
OcPlatform
gearstop = (Button) findViewById(R.id.Button07);
gearstop.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "stop button click listener");
+ Log.i(LOG_TAG, "stop button click listener");
m_pm.stopPlugins("ResourceType", "device.notify");
gearResource = null;
try {
geargetPlugins = (Button) findViewById(R.id.Button08);
geargetPlugins.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "getPlugins button click listener");
+ Log.i(LOG_TAG, "getPlugins button click listener");
user_plugin = m_pm.getPlugins();
state = "";
id = "";
geargetPlugins = (Button) findViewById(R.id.Button09);
geargetPlugins.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "getState click listener");
+ Log.i(LOG_TAG, "getState click listener");
state = m_pm.getState("gearnoti");
if (state == "")
state = "null";
gearrescan = (Button) findViewById(R.id.Button10);
gearrescan.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "Rescan Plugin click listener");
+ Log.i(LOG_TAG, "Rescan Plugin click listener");
m_pm.rescanPlugin();
try {
Thread.sleep(2000);
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");
+ Log.i(LOG_TAG, "Hue button click listener");
OcRepresentation rep = new OcRepresentation();
ToggleButton t = (ToggleButton) v;
if (t.isChecked()) {
Toast.makeText(getApplicationContext(), "Hue ON",
Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Hue ON");
if (hueplug.m_bright == 0) {
- Log.e("Felix", "hueplug m_bright is 0");
+ Log.e(LOG_TAG, "hueplug m_bright is 0");
hueplug.m_bright = 128;
}
try {
rep.setValue("brightness", hueplug.m_bright);
rep.setValue("color", hueplug.m_color);
} catch (OcException e) {
- Log.e("Felix", e.getMessage());
+ Log.e(LOG_TAG, e.getMessage());
}
OnPutHuebulb onPut = new OnPutHuebulb();
} else {
Toast.makeText(getApplicationContext(),
"HueResource null", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "HueResource null");
}
} else {
Toast.makeText(getApplicationContext(), "Hue OFF",
Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Hue OFF");
if (hueplug.m_bright == 0) {
- Log.e("Felix", "hueplug m_bright is 0");
+ Log.e(LOG_TAG, "hueplug m_bright is 0");
hueplug.m_bright = 128;
}
try {
rep.setValue("brightness", hueplug.m_bright);
rep.setValue("color", hueplug.m_color);
} catch (OcException e) {
- Log.e("Felix", e.getMessage());
+ Log.e(LOG_TAG, e.getMessage());
}
OnPutHuebulb onPut = new OnPutHuebulb();
onPut);
} catch (OcException e) {
e.printStackTrace();
+ Log.e(LOG_TAG, e.getMessage());
}
} else {
Toast.makeText(getApplicationContext(),
"HueResource null", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "HueResource null");
}
}
}
huestart = (Button) findViewById(R.id.Button11);
huestart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "start button click listener");
+ Log.i(LOG_TAG, "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!!!");
+ Log.i(LOG_TAG, "run called!!!");
FoundResource foundResource = new FoundResource();
try {
OcPlatform
huestop = (Button) findViewById(R.id.Button12);
huestop.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "stop button click listener");
+ Log.i(LOG_TAG, "stop button click listener");
m_pm.stopPlugins("ResourceType", "device.light");
hueResource = null;
try {
huegetPlugins = (Button) findViewById(R.id.Button13);
huegetPlugins.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "getPlugins button click listener");
+ Log.i(LOG_TAG, "getPlugins button click listener");
user_plugin = m_pm.getPlugins();
key = "name";
state = "";
huegetPlugins = (Button) findViewById(R.id.Button14);
huegetPlugins.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "getState click listener");
+ Log.i(LOG_TAG, "getState click listener");
state = m_pm.getState("hue");
if (state == "")
state = "null";
huerescan = (Button) findViewById(R.id.Button15);
huerescan.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
- Log.i("Felix", "Rescan Plugin click listener");
+ Log.i(LOG_TAG, "Rescan Plugin click listener");
m_pm.rescanPlugin();
try {
Thread.sleep(2000);
static public void updateConnectStatus(String device, boolean status) {
if (device.equals("belkinplug")) {
if (status) {
- Log.i("Felix", "belkingplug status green");
+ Log.i(LOG_TAG, "belkingplug status green");
Toast.makeText(mActivity.getApplicationContext(),
"Belkin Connected", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Belkin Connected");
} else {
- Log.i("Felix", "belkingplug status gray");
+ Log.i(LOG_TAG, "belkingplug status gray");
Toast.makeText(mActivity.getApplicationContext(),
"Belkin Disonnected", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Belkin Disonnected");
}
} else if (device.equals("gear")) {
if (status) {
- Log.i("Felix", "gear status green");
+ Log.i(LOG_TAG, "gear status green");
Toast.makeText(mActivity.getApplicationContext(),
"Gear Connected", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Gear Connected");
} else {
- Log.i("Felix", "gear status gray");
+ Log.i(LOG_TAG, "gear status gray");
Toast.makeText(mActivity.getApplicationContext(),
"Gear Disconnected", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Gear Disonnected");
}
} else if (device.equals("huebulb")) {
if (status) {
- Log.i("Felix", "huebulb status green");
+ Log.i(LOG_TAG, "huebulb status green");
Toast.makeText(mActivity.getApplicationContext(),
"Hue Connected", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Hue Connected");
} else {
- Log.i("Felix", "huebulb status gray");
+ Log.i(LOG_TAG, "huebulb status gray");
Toast.makeText(mActivity.getApplicationContext(),
"Hue Disconnected", Toast.LENGTH_SHORT).show();
+ Log.i(LOG_TAG, "Hue Disconnected");
}
if (hueplug.m_power.equals("on")) {
@Override
protected void onResume() {
- Log.i("Felix", "onResume()");
+ Log.i(LOG_TAG, "onResume()");
super.onResume();
}
@Override
protected void onPause() {
- Log.i("Felix", "onPause()");
+ Log.i(LOG_TAG, "onPause()");
super.onPause();
finish();
}
@Override
protected void onStop() {
- Log.i("Felix", "onStop()");
+ Log.i(LOG_TAG, "onStop()");
super.onStop();
}
@Override
protected void onDestroy() {
- Log.i("Felix", "onDestroy()");
+ Log.i(LOG_TAG, "onDestroy()");
System.exit(1);
super.onDestroy();
}
try {
sleep(1000, 0);
} catch (Exception e) {
- Log.i("Felix", "waitForFinal exception : " + e);
+ Log.i(LOG_TAG, "waitForFinal exception : " + e);
}
- Log.i("Felix", "Final Value for NUMBERPICKER[" + idx + "] : "
+ Log.i(LOG_TAG, "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);
+ Log.i(LOG_TAG, "m_color = " + hueplug.m_color);
OcRepresentation rep = new OcRepresentation();
if (hueplug.m_power == null) {
rep.setValue("brightness", hueplug.m_bright = 180);
rep.setValue("color", hueplug.m_color);
} catch (OcException e) {
- Log.e("Felix", e.getMessage());
+ Log.e(LOG_TAG, e.getMessage());
}
OnPutHuebulb onPut = new OnPutHuebulb();
if (hueResource != null) {
- Log.i("Felix", "huebulbResource is not null");
+ Log.i(LOG_TAG, "huebulbResource is not null");
try {
hueResource.put(rep, new HashMap<String, String>(),
onPut);
e.printStackTrace();
}
} else {
- Log.i("Felix", "huebulbResource is null");
+ Log.i(LOG_TAG, "huebulbResource is null");
}
}
onValueChangeThreadStart.put(idx, false);
import android.util.Log;
public class OnGetBelkinplug implements OcResource.OnGetListener {
- final private static String TAG = "OnGetBelkinplug";
+ final private static String TAG = "PPMSampleApp : OnGetBelkinplug";
@Override
public void onGetCompleted(List<OcHeaderOption> headerOptions,
import android.util.Log;
public class OnGetGear implements OcResource.OnGetListener {
- final private static String TAG = "OnGetGear";
+ final private static String TAG = "PPMSampleApp : OnGetGear";
@Override
public void onGetCompleted(List<OcHeaderOption> headerOptions,
import android.util.Log;
public class OnGetHuebulb implements OcResource.OnGetListener {
- final private static String TAG = "OnGetHuebulb";
+ final private static String TAG = "PPMSampleApp : OnGetHuebulb";
@Override
public void onGetCompleted(List<OcHeaderOption> headerOptions,
import android.util.Log;
public class OnPutBelkinplug implements OcResource.OnPutListener {
- final private static String TAG = "OnPutBelkinplug";
+ final private static String TAG = "PPMSampleApp : OnPutBelkinplug";
@Override
public void onPutCompleted(List<OcHeaderOption> options,
import android.util.Log;
public class OnPutGear implements OcResource.OnPutListener {
- final private static String TAG = "OnPutGear";
+ final private static String TAG = "PPMSampleApp : OnPutGear";
@Override
public void onPutCompleted(List<OcHeaderOption> options,
import android.util.Log;
public class OnPutHuebulb implements OcResource.OnPutListener {
- final private static String TAG = "OnPutHuebulb";
+ final private static String TAG = "PPMSampleApp : OnPutHuebulb";
@Override
public void onPutCompleted(List<OcHeaderOption> options,
System.loadLibrary("PluginManager");
}
+ private static final String LOG_TAG = "PPMSampleApp : PluginManager";
+
private native int jniStartPlugins(String key, String value);
private native int jniStopPlugins(String key, String value);
private native String jniGetState(String plugID);
private static void LogEx(String info) {
- Log.d("PluginManager.java", info);
+ Log.d(LOG_TAG, info);
}
}
if (path != ".")
path = "/data/data/" + path + "/files";
#elif __TIZEN__
- char *app_id = (char *)malloc(PATH_MAX_SIZE * sizeof(char));
- char completePath[PATH_MAX_SIZE];
+ char *app_id = NULL;
int res = app_get_id(&app_id);
if (APP_ERROR_NONE == res)
{
- strcpy(completePath, "/opt/usr/apps/");
- strcat(completePath, app_id);
- strcat(completePath, "/lib");
+ path = "/opt/usr/apps/";
+ path += app_id;
+ path += "/lib";
}
- path = completePath;
+ free(app_id);
#endif
if (loadConfigFile(path + "/pluginmanager.xml") != PM_S_OK)
PMRESULT Config::getXmlData(xml_node<> *pluginInfo, std::string key)
{
+ if(pluginInfo == NULL)
+ {
+ return PM_S_FALSE;
+ }
+
std::string value = "";
xml_attribute<> *iAttr = pluginInfo->first_attribute(key.c_str());
if (iAttr)
PluginManager::PluginManager()
{
#ifdef __TIZEN__
- char *app_id = (char *)malloc(PATH_MAX_SIZE * sizeof(char));
- char completePath[PATH_MAX_SIZE];
+ char *app_id = NULL;
+ std::string completePath = "";
int res = app_get_id(&app_id);
if (APP_ERROR_NONE == res)
{
- strcpy(completePath, "/opt/usr/apps/");
- strcat(completePath, app_id);
- strcat(completePath, "/lib/libpmimpl.so");
+ completePath = "/opt/usr/apps/";
+ completePath += app_id;
+ completePath += "/lib/libpmimpl.so";
}
- handle = dlopen(completePath, RTLD_LAZY);
+ free(app_id);
+ app_id = NULL;
+ handle = dlopen(completePath.c_str(), RTLD_LAZY);
#else
handle = dlopen("./libpmimpl.so", RTLD_LAZY);
#endif //#ifdef __TIZEN__
std::string PluginManager::getState(const std::string plugID)
{
return pluginManagerImpl->getState(plugID);
-}
\ No newline at end of file
+}
mosquitto = mosquitto_env.StaticLibrary('mosquitto', mosquitto_src)
mosquitto_env.InstallTarget(mosquitto, 'libmosquitto')
+mosquitto_env.UserInstallTargetLib(mosquitto, 'libmosquitto')
SConscript('cpp/SConscript')
######################################################################
mosquittopp = mosquittopp_env.SharedLibrary('mosquittopp', 'mosquittopp.cpp')
mosquittopp_env.InstallTarget(mosquittopp, 'libmosquittopp')
+mosquittopp_env.UserInstallTargetLib(mosquittopp, 'libmosquittopp')
sample_env.AppendUnique(LIBS = ['oc', 'oc_logger', 'octbstack',
'connectivity_abstraction', 'coap',
- 'ppm', 'pmimpl', 'dl'])
+ 'ppm', 'boost_system', 'pmimpl', 'dl'])
if env.get('SECURED') == '1':
sample_env.AppendUnique(LIBS = ['tinydtls'])
// 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";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.fan";
OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResourceFan);
std::cout << "Finding Resource... " << std::endl;
while (true)
sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
strcat(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
sprintf(buf, "onObserve Response error: = %d<br>", eCode);
strcpy(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
std::exit(-1);
sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
strcat(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
}
sprintf(buf, "onPost Response error: = %d<br>", eCode);
strcpy(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
std::exit(-1);
sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
strcat(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
}
sprintf(buf, "onPost Response error: = %d<br>", eCode);
strcpy(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
std::exit(-1);
sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
strcat(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
sprintf(buf, "onPut Response error: = %d<br>", eCode);
strcpy(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
std::exit(-1);
sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
strcat(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
sprintf(buf, "onGET Response error: = %d<br>", eCode);
strcpy(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
std::exit(-1);
putFanRepresentation(curFanResource);
}
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
}
std::cout << "Resource is invalid" << std::endl;
strcpy(temp_string, "Resource is invalid");
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
}
sprintf(buf, "value ID = %s<br>", user_plugin[i].getID().c_str());
strcat(temp_string, buf);
m_ThreadContext.log = temp_string;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
std::cout << "value Name = " << user_plugin[i].getName() << 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;
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", m_ThreadContext.log);
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
&m_ThreadContext);
m_pm->startPlugins("ResourceType", "oic.fan");
// Find fan resources
std::ostringstream requestURI;
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.fan";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.fan";
OCPlatform::findResource("", requestURI.str(), OC_ALL, &foundResourceFan);
std::cout << "Finding Resource... " << std::endl;
}
source = [ssm_sdk_cpp_src]
)
sdk_env.InstallTarget(libssmsdk, 'libSSMCORE')
+sdk_env.UserInstallTargetLib(libssmsdk, 'libSSMCORE')
######################################################################
# build DiscomfortIndexSensor plugin
DiscomfortIndexSensor = DiscomfortIndexSensor_env.SharedLibrary('DiscomfortIndexSensor', DiscomfortIndexSensor_src)
DiscomfortIndexSensor_env.InstallTarget(DiscomfortIndexSensor, 'libDiscomfortIndexSensor')
+DiscomfortIndexSensor_env.UserInstallTargetLib(DiscomfortIndexSensor, 'libDiscomfortIndexSensor')
BMISensor = BMISensor_env.SharedLibrary('BMISensor', BMISensor_src)
BMISensor_env.InstallTarget(BMISensor, 'libBMISensor')
+BMISensor_env.UserInstallTargetLib(BMISensor, 'libBMISensor')
)
ssmcore_env.InstallTarget([shared_libssmcore, static_libssmcore], 'libSSMCORE')
+ssmcore_env.UserInstallTargetLib([shared_libssmcore, static_libssmcore], 'libSSMCORE')
#######################################################################
## build SampleApp
for (unsigned int j = 0; j < (result_model_data_id)[i].dataId.size(); j++)
{
- CModelData *pModelData = new CModelData();
+ CModelData *pModelData = NULL;
IContextModel *pCM = NULL;
ModelPropertyVec modelPropertyVec;
SSM_CLEANUP_ASSERT(m_pPropagationEngine->getContextModel((result_model_data_id)[i].modelName,
&pCM));
SSM_CLEANUP_ASSERT(pCM->getModelData((result_model_data_id)[i].dataId[j], &modelPropertyVec));
+ pModelData = new CModelData();
pModelData->setDataId((result_model_data_id)[i].dataId[j]);
for (ModelPropertyVec::iterator itor = modelPropertyVec.begin();
itor != modelPropertyVec.end(); ++itor)
pData[0] = EVENT_TYPE_OUTER;
pData[1] = userTriggerId;
pData[2] = reinterpret_cast<intptr_t>(pDataReader);
+ pDataReader = NULL;
m_pTasker->addTask(this, (void *)pData);
CLEANUP:
m_mtxQueries.unlock();
+ SAFE_DELETE(pDataReader);
SAFE_RELEASE(temp_contextmodel);
SAFE_RELEASE(temp_contextmodel2);
return res;
pConditionedQuery->addRef();
m_conditionedQueries[m_cqid] = pConditionedQuery;
m_contextQueries[m_cqid] = clsContextQuery;
+ clsContextQuery = NULL; //Mark it NULL, so that it's not freed in CLEANUP.
m_mtxQueries.unlock();
if (pConditionedQuery->hasAllConditionedModels() == true)
CLEANUP:
SAFE_RELEASE(pConditionedQuery);
SAFE_RELEASE(pConditionedQueryResult);
+ SAFE_DELETE(clsContextQuery);
return res;
}
OCStackResult ret = OC_STACK_ERROR;
std::ostringstream requestURI;
- requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=SSManager.Sensor";
+ requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=SSManager.Sensor";
std::ostringstream multicastPresenceURI;
multicastPresenceURI << "coap://" << OC_MULTICAST_PREFIX;
case RESOURCE_DISCOVER_REQUESTPROFILE:
pResource = (std::shared_ptr< OC::OCResource > *) pMessage[1];
pResourceHandler = new OICResourceHandler();
- SSM_CLEANUP_ASSERT(pResourceHandler->initHandler(*pResource, this));
+
+ res = pResourceHandler->initHandler(*pResource, this);
+ if(res != SSM_S_OK)
+ {
+ SAFE_DELETE(pResourceHandler);
+ SSM_CLEANUP_ASSERT(res);
+ }
resourceFullPath = pResource->get()->host() + pResource->get()->uri();
private ArrayList<Integer> mRunningQueries = new ArrayList<Integer>();
private IQueryEngineEvent mQueryEngineEventListener = null;
- private final String LOG_TAG = this.getClass().getSimpleName();
+ private final String LOG_TAG = "SSMSampleApp : " + this.getClass().getSimpleName();
private static MainActivity activityObj;
void PrintLog(String log) {
data.putString("Log", log);
msg.setData(data);
logHandler.sendMessage(msg);
+ Log.i(LOG_TAG, log);
}
private Handler logHandler = new Handler() {
switch (v.getId()) {
case R.id.btClear:
edtQuery.setText("");
+ Log.i(LOG_TAG, "Query textbox is cleared");
break;
case R.id.btLogClear:
tvLog.setText("");
+ Log.i(LOG_TAG, "Log textbox is cleared");
break;
case R.id.btFullDevice:
edtQuery.setText("subscribe Device if Device.dataId != 0");
+ Log.i(LOG_TAG, "subscribe Device if Device.dataId != 0");
break;
case R.id.btDiscomfortIndex:
edtQuery.setText("subscribe Device.DiscomfortIndexSensor if Device.DiscomfortIndexSensor.discomfortIndex > 0");
+ Log.i(LOG_TAG, "subscribe Device.DiscomfortIndexSensor if Device.DiscomfortIndexSensor.discomfortIndex > 0");
break;
}
}
OCResourceHandle m_handle;
-
-
Cble ble;
char trackeeID[13] = "9059AF16FEF7";
int slaver_num = 0;
char slaveList[SLAVER_EA][13] = {"9059AF1700EE", "34B1F7D004D2"};
int g_PROXIUnderObservation = 0;
-
-
const char *getResult(OCStackResult result);
void createResource();
-
#define LENGTH_VAR 50
bool JsonGenerator( char *jsonBuf, uint16_t buf_length )
{
-
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.
{
OCEntityHandlerResult ehRet = OC_EH_OK;
- if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+ if (entityHandlerRequest )
{
- OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
- if (OC_REST_GET == entityHandlerRequest->method)
+ if (flag & OC_REQUEST_FLAG)
{
- if ( JsonGenerator( (char *)entityHandlerRequest->resJSONPayload,
- entityHandlerRequest->resJSONPayloadLen ) == false )
+ OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
+ if (OC_REST_GET == entityHandlerRequest->method)
{
- ehRet = OC_EH_ERROR;
+ 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 )
+ if (OC_REST_PUT == entityHandlerRequest->method)
{
- ehRet = OC_EH_ERROR;
+ 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)
+ else if (flag & OC_OBSERVE_FLAG)
{
- OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
+ OC_LOG (INFO, TAG, PCF("Flag includes 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);
+ Serial.println((char *)entityHandlerRequest->resJSONPayload);
+ }
return ehRet;
}
-
-
-
-
-
-
//The setup function is called once at startup of the sketch
void setup()
{
ble.init( (long)115200, BLE_SLAVER, slaveList[0]);
-
// ble.StatusRead();
OC_LOG_V(INFO, TAG, "Program Start-\r\n");
{
// 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"));
}
-
-
-
-
-
-
void createResource()
{
OIC::IModelData *pModelData = NULL;
std::vector<std::string> affectedModels;
- dlog_print(DLOG_ERROR, LOG_TAG, "Event received!");
+ dlog_print(DLOG_INFO, LOG_TAG, "Event received! cqid = %d", cqid);
sprintf(buf, "Event received! cqid = %d<br>", cqid);
strcpy(log, buf);
for (int i = 0; i < dataCount; i++)
{
pResult->getModelData(*itor, i, &pModelData);
+ dlog_print(DLOG_INFO, LOG_TAG, "dataId: %d<br>", pModelData->getDataId());
sprintf(buf, "dataId: %d<br>", pModelData->getDataId());
strcat(log, buf);
for (int j = 0; j < pModelData->getPropertyCount(); j++)
{
+ dlog_print(DLOG_INFO, LOG_TAG, "Type: %s Value: %s<br>",
+ (pModelData->getPropertyName(j)).c_str(),
+ (pModelData->getPropertyValue(j)).c_str());
sprintf(buf, "Type: %s Value: %s<br>",
(pModelData->getPropertyName(j)).c_str(),
(pModelData->getPropertyValue(j)).c_str());
if (res == OIC::SSM_S_OK)
{
updateLog(ad, "The query has been registered!<br>");
+ dlog_print(DLOG_INFO, LOG_TAG, "QID : %d\n", qid);
sprintf(log, "QID : %d<br>", qid);
updateLog(ad, log);
}
else
{
+ dlog_print(DLOG_INFO, LOG_TAG, "Error occured(%d)\n", res);
sprintf(log, "Error occured(%d)<br>", res);
updateLog(ad, log);
}
try
{
int val = atoi(query_id_str);
+ dlog_print(DLOG_INFO, LOG_TAG, "%d", val - 1);
sprintf(output, "%d", val - 1);
elm_entry_entry_set(ad->unregister_query_id, output);
}
try
{
int val = atoi(query_id_str);
+ dlog_print(DLOG_INFO, LOG_TAG, "%d", val + 1);
sprintf(output, "%d", val + 1);
elm_entry_entry_set(ad->unregister_query_id, output);
}
if (res == OIC::SSM_S_OK)
{
updateLog(ad, "The query has been unregistered!<br>");
+ dlog_print(DLOG_INFO, LOG_TAG, "QID : %d\n", qid);
sprintf(log, "QID : %d<br>", qid);
updateLog(ad, log);
}
else
{
+ dlog_print(DLOG_INFO, LOG_TAG, "Error occured(%d)\n", res);
sprintf(log, "Error occured(%d)<br>", res);
updateLog(ad, log);
}
tgmsdk_shared = things_manager_env.SharedLibrary('TGMSDKLibrary', tgm_src)
things_manager_env.InstallTarget([tgmsdk_static,tgmsdk_shared], 'libTGMSDK')
+things_manager_env.UserInstallTargetLib([tgmsdk_static,tgmsdk_shared], 'libTGMSDK')
# Build JNI layer
#if target_os == 'android':
*/
public class ActionListener implements IActionListener {
- private final String LOG_TAG = this.getClass()
- .getSimpleName();
+ private final String LOG_TAG = "[TMSample] " + this.getClass()
+ .getSimpleName();
private static Message msg;
private String logMessage;
private GroupApiActivity groupApiActivityObj = null;
case 0:
logs.setText("");
logs.setText(logMessage);
+ Log.i(LOG_TAG, logMessage);
}
}
};
.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);
.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;
}
.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;
}
.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;
}
private void displayToastMessage(String message) {
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
+ Log.i(LOG_TAG, message);
}
private void collectionFound(OcResource resource) {
*/
public class ConfigurationListener implements IConfigurationListener {
- private final String LOG_TAG = this.getClass().getSimpleName();
+ private final String LOG_TAG = "[TMSample] " + this.getClass().getSimpleName();
@Override
public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
*/
public class DiagnosticListener implements IDiagnosticsListener {
- private final String LOG_TAG = this.getClass().getSimpleName();
+ private final String LOG_TAG = "[TMSample] " + this.getClass().getSimpleName();
@Override
public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
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;
// For Scheduled ActionSet
public static Context mcontext;
public static Calendar scheduleTime;
+
+ private final String LOG_TAG = "[TMSample] " + this.getClass()
+ .getSimpleName();;
@Override
protected void onCreate(Bundle savedInstanceState) {
case 1:
logs.setText("");
logs.setText(logMessage);
+ Log.i(LOG_TAG, logMessage);
}
}
};
public void displayToastMessage(String message) {
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
+ Log.i(LOG_TAG, message);
}
}
*/
public class GroupClient {
- private static final String LOG_TAG = "GroupClient";
+ private static final String LOG_TAG = "[TMSample] GroupClient";
private static Message msg;
public String logMessage;
String uri = resource.getUri();
if (uri.equals("/b/collection") == true) {
String hostAddress = resource.getHost();
- Log.d("URI: onGroupFindCallback", uri);
- Log.d("HOST: onGroupFindCallback", hostAddress);
+ Log.d(LOG_TAG, "onGroupFindCallback URI : " + uri);
+ Log.d(LOG_TAG, "onGroupFindCallback HOST : " + hostAddress);
groupResource = resource;
Message msg = Message.obtain();
msg.what = 1;
groupApiActivityObj.getHandler().sendMessage(msg);
} else {
- Log.d("onGroupFindCallback URI : ", uri);
+ Log.d(LOG_TAG, "onGroupFindCallback URI : " + uri);
}
} else {
Log.i(LOG_TAG, "Resource is NULL");
private ArrayAdapter<String> apis;
private ArrayList<String> apisList;
private ListView list;
- private final String LOG_TAG = this.getClass()
- .getSimpleName();
+ private final String LOG_TAG = "[TMSample] " + this.getClass()
+ .getSimpleName();
public ThingsManager thingsManagerObj = new ThingsManager();
@Override
dialog = dialogBuilder.create();
dialog.show();
+ Log.i(LOG_TAG, "WiFi is not enabled/connected! Please connect the WiFi and start application again...");
return;
}
// If wifi is connected calling the configure method for configuring the
*/
public class MainActivity extends Activity {
- private final String LOG_TAG = this.getClass().getSimpleName();
+ private final String LOG_TAG = "[CON-SERVER]" + this.getClass().getSimpleName();
private Handler mHandler;
private static MainActivity mainActivityObj;
private ConfigurationServer conServerObj;
switch (msg.what) {
case 0:
editText.setText(message);
+ Log.i(LOG_TAG, message);
}
}
};
AlertDialog dialog = dialogBuilder.create();
dialog.show();
+ Log.i(LOG_TAG, "WiFi is not enabled/connected! Please connect the WiFi and start application again...");
return;
}
dialog.setProgress(0);
dialog.setMax(100);
dialog.show();
+ Log.i(LOG_TAG, "Rebooting.. Please wait ...");
Thread thread = new Thread() {
@Override
public void run() {
conclient = linux_sample_env.Program('con-client', 'con-client.cpp')
bootstrapserver = linux_sample_env.Program('bootstrapserver', 'bootstrapserver.cpp')
Alias("ConServerApp", conserver)
-Alias("ConCleintApp", conclient)
+Alias("ConClientApp", conclient)
Alias("BootstrapServerApp", bootstrapserver)
env.AppendTarget('ConServerApp')
env.AppendTarget('ConClientApp')
if (n == 9)
{
- std::string query = OC_MULTICAST_DISCOVERY_URI;
+ std::string query = OC_RSRVD_WELL_KNOWN_URI;
query.append("?rt=");
query.append(resourceTypeName);
}
else if (n == 0)
{
- std::string query = OC_MULTICAST_DISCOVERY_URI;
+ std::string query = OC_RSRVD_WELL_KNOWN_URI;
query.append("?rt=");
query.append("core.bookmark");
phone = linux_sample_env.Program('phone', 'phone.cpp')
speaker = linux_sample_env.Program('speaker', 'speaker.cpp')
Alias("GroupApp", group)
-Alias("ConCleintApp", musicplayer)
+Alias("MusicplayerApp", musicplayer)
Alias("PhoneApp", phone)
Alias("SpeakerApp", speaker)
env.AppendTarget('GroupApp')
{
cout << "onFindResource" << endl;
- if (resource)
+ try
{
- OCResourceHandle resourceHandle;
- OCStackResult result = OCPlatform::registerResource(resourceHandle, resource);
- if (OC_STACK_OK == result)
- {
- cout << "onFindResource : Resource creation was successful\n";
- }
- else
+ if (resource)
{
- cout << "onFindResource : Resource creation was unsuccessful\n";
- return;
- }
+ OCResourceHandle resourceHandle;
+ OCStackResult result = OCPlatform::registerResource(resourceHandle, resource);
+ if (OC_STACK_OK == result)
+ {
+ cout << "onFindResource : Resource creation was successful\n";
+ }
+ else
+ {
+ cout << "onFindResource : Resource creation was unsuccessful\n";
+ return;
+ }
- result = gThingManager->joinGroup(collectionResourceType, resourceHandle);
- if (OC_STACK_OK == result)
- {
- cout << "onFindResource : Joining group was successful\n";
+ result = gThingManager->joinGroup(collectionResourceType, resourceHandle);
+ if (OC_STACK_OK == result)
+ {
+ cout << "onFindResource : Joining group was successful\n";
+ }
+ else
+ {
+ cout << "onFindResource : Joining group was unsuccessful\n";
+
+ OCPlatform::unregisterResource(resourceHandle);
+ return;
+ }
+
+ gResourceHandleList.push_back(resourceHandle);
}
else
{
- cout << "onFindResource : Joining group was unsuccessful\n";
-
- OCPlatform::unregisterResource(resourceHandle);
- return;
+ cout << "onFindResource : There is no found resource." << endl;
}
-
- gResourceHandleList.push_back(resourceHandle);
- }
- else
+ }catch (std::exception& e)
{
- cout << "onFindResource : There is no found resource." << endl;
+ std::cout << "Exception: " << e.what() << std::endl;
}
}
else if (selectedMenu == 11)
{
ostringstream query;
- query << OC_MULTICAST_DISCOVERY_URI << "?rt=core.musicplayer";
+ query << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.musicplayer";
cout << query.str() << endl;
result = OCPlatform::findResource("",
CT_DEFAULT,
onFindResource);
- result = OCPlatform::findResource("",
- "coap://224.0.1.187/oc/core?rt=core.musicplayer",
- CT_DEFAULT,
- onFindResource);
-
if (OC_STACK_OK == result)
{
cout << "Finding music player was successful\n";
else if (selectedMenu == 12)
{
ostringstream query;
- query << OC_MULTICAST_DISCOVERY_URI << "?rt=core.speaker";
+ query << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.speaker";
result = OCPlatform::findResource("",
query.str(),
CT_DEFAULT,
OCPlatform::Configure(cfg);
+ OCPlatform::startPresence(30);
+
int selectedMenu;
OCStackResult result;
OCResourceHandle mpResourceHandle = NULL;
static ActionSet* gPlayStop;
+void presenceCallback(std::string msg, OCStackResult res)
+{
+ std::cout << "Presence Callback: " << msg << "(" << res << ")" << std::endl;
+}
+
void onFindGroup(std::shared_ptr< OCResource > resource)
{
if (resource)
{
cout << "onFindGroup : Found group is saved now." << endl;
gFindGroup = resource;
+ {
+ OCStackResult res;
+ res = gThingManager->subscribeCollectionPresence( resource, &presenceCallback);
+
+ std::cout << "Return Value: " << res << std::endl;
+ }
}
gThingManager->joinGroup(gFindGroup, gPhoneResourceHandle);
OCPlatform::Configure(cfg);
+ OCPlatform::startPresence(30);
+
int selectedMenu;
OCStackResult result;
OCResourceHandle speakerResourceHandle = NULL;
if (OC_STACK_OK == sendResponseForResource(request))
{
ehResult = OC_EH_OK;
+ dlog_print(DLOG_INFO, LOG_TAG, "#### sendResponse success.");
}
else
{
elm_entry_entry_append(log_entry, log->c_str());
elm_entry_cursor_end_set(log_entry);
+ dlog_print(DLOG_INFO, LOG_TAG, "%s", log->c_str());
dlog_print(DLOG_INFO, LOG_TAG, "#### updateLog exit!!!!");
return NULL;
logMessage += "currency : " + defaultCurrency + "<br>";
logMessage += "Region : " + defaultRegion + "<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+
//Call updateLog in the thread safe mode
ecore_main_loop_thread_safe_call_sync(updateLog, &logMessage);
{
logMessage += "Resources were created already!!! <br>";
}
+
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
// Show the log in the UI
ecore_main_loop_thread_safe_call_sync(updateLog, &logMessage);
}
logMessage = "----------------------------<br>";
logMessage += "*** System Reboot Success ***<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
//Show the log
ecore_main_loop_thread_safe_call_sync(updateLog, &logMessage);
logMessage += "----------------------<br>";
dlog_print(DLOG_INFO, LOG_TAG, "FoundHost: %s", resourceURI.c_str());
dlog_print(DLOG_INFO, LOG_TAG, "FoundUri : %s", hostAddress.c_str());
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
&logMessage);
else
{
// Resource is invalid
+
logMessage = "Found Resource invalid!";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
&logMessage);
}
logMessage += "----------------------<br>";
dlog_print(DLOG_INFO, LOG_TAG, "Host: %s", resourceURI.c_str());
dlog_print(DLOG_INFO, LOG_TAG, "Uri : %s", hostAddress.c_str());
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
&logMessage);
logMessage = logMessage + "Region : " + rep.getValue< std::string >("r") + "<br>";
}
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
&logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### onUpdateConfigurationsCallback: EXIT!!!!");
}
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### onGetConfigurationsCallback: exit!!!!");
}
logMessage = logMessage + "FactoryReset : " +
rep.getValue< std::string >("value") + "<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### onFactoryReset: exit!!!!");
}
logMessage = logMessage + "Reboot : " +
rep.getValue< std::string >("value") + "<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### onReboot: exit!!!!");
}
string logMessage;
logMessage = "Resource created : <br>" + typeName + "<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### createResourceCollection: exit!!!!");
}
{
dlog_print(DLOG_ERROR, LOG_TAG, "Note that you first create a group to use this command");
string logMessage = "FIRST CREATE GROUP <br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
return;
}
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>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
return;
}
{
string logMessage = "UpdateConfigurations called successfully<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
}
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>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
return;
}
{
string logMessage = "FactoryReset called successfully<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
}
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>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
return;
}
{
string logMessage = "Reboot called successfully<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
}
dlog_print(DLOG_INFO, LOG_TAG, "#### reboot EXIT!!!!");
string logMessage;
logMessage = "Supported Configuration List :<br>" + listOfSupportedConfigurationUnits + "<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### getListOfSupportedConfigurationUnits EXIT!!!!");
}
dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL RegionValue");
string logMessage = "Region Value should not be NULL<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
}
else
{
dlog_print(DLOG_ERROR, LOG_TAG, "Note that you first create a group to use this command");
string logMessage = "FIRST CREATE GROUP <br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
return;
}
if (NULL == popup_fields)
{
dlog_print(DLOG_INFO, LOG_TAG, "#### Memory allocation failed");
- popup_fields->popup = NULL;
- popup_fields->entry = NULL;
}
else
{
dlog_print(DLOG_INFO, LOG_TAG, "#### Invalid Parameter");
}
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
}
}
}
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### onPost callback received EXIT!!!!");
string logMessage = "NO LIGHTSERVER FOUND <br>";
logMessage += "----------------------<br>";
dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
delete actionSet;
string logMessage = "Create actionset AllBulbOFF success <br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### createActionSet_AllBulbOff EXIT");
}
string logMessage = "Create actionset AllBulbON success <br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### createActionSet_AllBulbOff OFF EXIT");
}
string logMessage = "Actionset OFF called successfully <br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### executeActionSetOff EXIT");
}
string logMessage = "Actionset ON called successfully <br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### executeActionSetOn EXIT");
}
string logMessage = "Actionset OFF DELETED <br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### deleteActionSetOff EXIT");
}
string logMessage = "Actionset ON DELETED <br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
dlog_print(DLOG_INFO, LOG_TAG, "#### deleteActionSetOn EXIT");
}
}
sprintf(buf, "%d", level);
logMessage += "level:" + string(buf) + "<br>";
+ free(buf);
}
else
{
logMessage = "onObserve error!!!";
}
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
}
(*rsrc)->observe(ObserveType::Observe, QueryParamsMap(), &onObserve);
dlog_print(DLOG_INFO, LOG_TAG, "#### after calling observe() for bookmark!!!!");
}
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
}
dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL DateTime Value");
string logMessage = "DateTime should not be NULL<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
}
else
dlog_print(DLOG_INFO, LOG_TAG, "#### Incorrect date/time values");
string logMessage = "Incorrect date/time value<br>";
logMessage += "----------------------<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
}
if (NULL == popup_fields)
{
dlog_print(DLOG_INFO, LOG_TAG, "#### Memory allocation failed");
- popup_fields->popup = NULL;
- popup_fields->entry = NULL;
}
else
{
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showGroupAPIs, NULL);
}
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
}
tm_jni = tm_jni_env.SharedLibrary('things-manager-jni', tm_jni_src)
tm_jni_env.InstallTarget(tm_jni, 'libthings-manager-jni')
+tm_jni_env.UserInstallTargetLib(tm_jni, 'libthings-manager-jni')
# Install the libraries to /libs/<TARGET_ARCH> directory
tm_jni_env.Install(tm_sdk+'/java/libs/'+tm_jni_env.get('TARGET_ARCH'),tm_jni_env.get('BUILD_DIR')+'/liboc_logger.so')
*
*/
-#include "GroupManager.h"
#include <algorithm>
#include <thread>
#include <unistd.h>
-
#include <string.h>
+#include "GroupManager.h"
+
#define PLAIN_DELIMITER "\""
#define ACTION_DELIMITER "*"
#define DESC_DELIMITER "|"
{
// std::cout << "resourceTypes : " << resourceTypes.at(i) << std::endl;
- std::string query = OC_MULTICAST_DISCOVERY_URI;
+ std::string query = OC_RSRVD_WELL_KNOWN_URI;
query.append("?rt=");
query.append(resourceTypes.at(i));
char *plainPtr = NULL;
char *attr = NULL, *desc = NULL;
+ Action *action = NULL;
Capability *capa = NULL;
ActionSet *actionset = new ActionSet();
if (desc != NULL)
{
- Action *action = NULL;
strcpy(desc, token);
token = strtok_r(desc, DESC_DELIMITER, &descPtr);
token = strtok_r(attr, ATTR_DELIMITER, &attrPtr);
while (token != NULL)
{
- if (strcmp(token, "uri") == 0)
+ if ( (action == NULL) && strcmp(token, "uri") == 0) //consider only first "uri" as uri, other as attribute.
{
token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
if(token == NULL)
}
if( action != NULL )
+ {
actionset->listOfAction.push_back(action);
+ action = NULL;
+ }
else
goto exit;
//delete action;
token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
}
- DELETE(plainText);
+ DELETEARRAY(plainText);
return actionset;
exit:
+ DELETE(action);
DELETE(capa)
DELETE(actionset)
DELETEARRAY(attr);
for (unsigned int i = 0; i < collectionResourceTypes.size(); ++i)
{
- std::string query = OC_MULTICAST_DISCOVERY_URI;
+ std::string query = OC_RSRVD_WELL_KNOWN_URI;
query.append("?rt=");
query.append(collectionResourceTypes.at(i));
if (methodType == "joinGroup")
{
- std::string resourceName = OC_MULTICAST_DISCOVERY_URI;
+ std::string resourceName = OC_RSRVD_WELL_KNOWN_URI;
resourceName.append("?rt=");
resourceName.append(resourceType);
OC_LOG_V(DEBUG, TAG, "\t\t\tresourceName : %s", resourceName.c_str());
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, conf)));
- free(newActionSet);
+ delete(newActionSet);
}
}
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, diag)));
- free(newActionSet);
+ delete(newActionSet);
}
}
scp -p -P 29418 ${GIT_USER}@gerrit.iotivity.org:hooks/commit-msg iotivity/.git/hooks/
fi
-export CEREAL_DIR=iotivity/extlibs/cereal
+export TINYCBOR_DIR=iotivity/extlibs/tinycbor
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
+ git clone https://github.com/01org/tinycbor ${CEREAL_DIR}
fi
#######################################
-# Android
+# Android
#######################################
echo "Set up Android NDK"