to skip it.
-=== Build IoTivity project on Linux(Ubuntu) ===
+=== Build IoTivity project ===
-1. Build IoTivity project for Linux
- $ cd <top directory of the project>
- $ sudo apt-get install libboost-dev libexpat1-dev libboost-thread-dev libssl-dev
- $ scons
+Linux:
+ * Possible values for <TARGET_TRANSPORT> are: ALL, IP, BLE
-2. Build IoTivity project for Android
- $ cd <top directory of the project>
- $ scons TARGET_OS=android TARGET_ARCH=xxx
-(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard. To see all of its
-allowed value, please execute command 'scons TARGET_OS=android -Q -h')
-
-3. Build IoTivity project for Arduino
- $ cd <top directory of the project>
- $ sudo apt-get install dos2unix
- $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy SHIELD=zzz
-(xxx can be avr, arm; yyy is the name of the board, zzz is the shield type, to
-get allowed values run: scons TARGET_OS=arduino TARGET_ARCH=xxx SHIELD=zzz -h.
-You may see a option 'CPU' in the output of above command line, that's due to
-some boards have different processors, to specify the processor, add 'CPU=zzz'
-in the command line. If no 'CPU' option exists, that means the board only
-support one kind of processor, it's unnecessary to specify it)
+1. Go to root directory
+ $ cd <top directory of the project>
+ $ sudo apt-get install libboost-dev libboost-thread-dev libssl-dev libtool
+
+2. Execute following command(s) to start build based on transport selection required
+
+ -> Building for all transports :
+ $ scons TARGET_OS=linux TARGET_TRANSPORT=ALL
+
+ -> Building for a specific transport :
+ $ scons TARGET_OS=linux TARGET_TRANSPORT=IP
+
+ -> Building for multiple transports :
+ $ scons TARGET_OS=linux TARGET_TRANSPORT=IP,BLE TARGET_ARCH=xxx
+
+ -> Clean Build (all transports) :
+ $ scons TARGET_OS=linux TARGET_TRANSPORT=ALL -c (for clean)
+
+Android:
+ * Possible values for <TARGET_TRANSPORT> are: ALL, IP, BT, BLE
+ * Possible values for <TARGET_ARCH> are: x86, armeabi, armeabi-v7a, armeabi-v7a-hard
+ (To see all of its allowed value, please execute command 'scons TARGET_OS=android -Q -h')
+
+1. Go to root directory
+ $ cd <top directory of the project>
+
+2. Execute following command(s) to start build based on transport selection required
+
+ -> Building for all transports :
+ $ scons TARGET_OS=android TARGET_TRANSPORT=ALL TARGET_ARCH=xxx
+
+ -> Building for a specific transport :
+ $ scons TARGET_OS=android TARGET_TRANSPORT=IP TARGET_ARCH=xxx
+
+ -> Building for multiple transports :
+ $ scons TARGET_OS=android TARGET_TRANSPORT=IP,BT,BLE TARGET_ARCH=xxx
+
+ -> Clean Build (all transports) :
+ $ scons TARGET_OS=android TARGET_TRANSPORT=ALL -c (for clean)
+
+Tizen:
+ * Possible values for <TARGET_TRANSPORT> are: ALL, IP, BT, BLE
+
+ 1. Go to root directory
+ $ cd <top directory of the project>
+
+ 2. Execute following command(s) to start build based on transport selection required
+
+ -> Building for all transports :
+ $ scons TARGET_OS=tizen TARGET_TRANSPORT=ALL
+
+ -> Building for a specific transport :
+ $ scons TARGET_OS=tizen TARGET_TRANSPORT=IP
+
+ -> Building for multiple transports :
+ $ scons TARGET_OS=tizen TARGET_TRANSPORT=IP,BT,BLE TARGET_ARCH=xxx
+
+ -> Clean Build (all transports) :
+ $ scons TARGET_OS=tizen TARGET_TRANSPORT=ALL -c (for clean)
-4. Build Iotivity project for Tizen
- $ cd <top directory of the project>
- $ sh gbsbuild.sh
(we provide the spec file required by gbs tool at toools/tizen directory.
gbs is default build tool for Tizen platfrom, we can refer the following
wiki to setup Tizen development environment:
https://source.tizen.org/documentation/developer-guide/getting-started-guide)
-Note: Currently most IoTivity project doesn't support Windows, so you can't set
+Arduino:
+ * Possible values for <TARGET_TRANSPORT> are: IP, BLE
+ * Possible values for <TARGET_ARCH> are: arv, arm
+ (arv: arduino due, arm: arduino mega)
+ * Possible values for <BOARD> are: arduino_due_x_dbg, arduino_due_x, mega
+ * Possible values for <SHIELD> are: ETH, WIFI
+ (It is required in the case of the arduino due.)
+
+ 1. Go to root directory
+ $ cd <top directory of the project>
+ $ sudo apt-get install dos2unix
+
+ 2. Execute following command(s) to start build based on transport selection required
+
+ -> Building for a specific transport :
+ $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy SHIELD=zzz
+
+(To get allowed values run: scons TARGET_OS=arduino TARGET_ARCH=xxx SHIELD=zzz -h.
+You may see a option 'CPU' in the output of above command line, that's due to
+some boards have different processors, to specify the processor, add 'CPU=zzz'
+in the command line. If no 'CPU' option exists, that means the board only
+support one kind of processor, it's unnecessary to specify it)
+
+Mac OSX:
+ * Possible values for <SYS_VERSION> are: OSX version, e.g. 10.9
+
+ 1. Go to root directory
+ $ cd <top directory of the project>
+
+ 2. Execute following command(s) to start build based on transport selection required
+
+ -> Building for a specific transport :
+ $ scons SYS_VERSION=yyy
+
+IOS:
+ * Possible values for <TARGET_ARCH> are: i386, x86_64, armv7, armv7s, arm64
+ * Possible values for <SYS_VERSION> are: IOS version, e.g. 7.0
+
+ 1. Go to root directory
+ $ cd <top directory of the project>
+
+ 2. Execute following command(s) to start build based on transport selection required
+
+ -> Building for a specific transport :
+ $ scons TARGET_OS=ios TARGET_ARCH=xxx SYS_VERSION=yyy
+
+* Additional options
+ * VERBOSE=true or false (Show compilation)
+ * RELEASE=true or false (Build for release?)
+ * LOGGING=true or false (Enable stack logging)
+ * SECURED=1 or 0 (Build with DTLS)
+ * TEST=1 or 0 (Run unit tests)
+ * SECURED=1 or 0 (Build with DTLS)
+ * BUILD_SAMPLE=ON or OFF (Build with sample)
+ * ROUTING=GW or EP (Enable routing)
+ * WITH_TCP=true or false (Enable CoAP over TCP Transport, arduino is not supported)
+ * WITH_RA=true or false (Build with Remote Access module)
+ * WITH_RD=1 or 0 (Build including Resource Directory)
+ * SIMULATOR=true or false (Build with simulator module)
+
+Note1: Currently most IoTivity project doesn't support Windows, so you can't set
TARGET_OS to 'windows' except the project support Windows.
That's to say if the project doesn't support Windows, run:
$ scons
may always fail.
-
-=== Build IoTivity project on Mac OSX ===
-
-1. Build IoTivity project for Mac OSX
- $ cd <top directory of the project>
- $ scons SYS_VERSION=yyy
-(yyy is the OSX version, e.g. 10.9)
-
-2. Build IoTivity project for Android(It's the same as on Ubuntu)
- $ cd <top directory of the project>
- $ scons TARGET_OS=android TARGET_ARCH=xxx
-(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard)
-
-3. Build IoTivity project for IOS
- $ cd <top directory of the project>
- $ scons TARGET_OS=ios TARGET_ARCH=xxx SYS_VERSION=yyy
-(xxx can be i386, x86_64, armv7, armv7s, arm64, yyy is IOS version, e.g. 7.0)
-
-Note:
+Note2:
1) for convenience, a script (auto_build.sh) is provided to run possible build
at once. Following is the usage:
LOGI("CaInterface_initialize");
CANativeJNISetContext(env, context);
-
- CAResult_t res = CAInitialize();
-
- if (CA_STATUS_OK != res)
- {
- LOGE("Could not Initialize");
- }
}
\ No newline at end of file
{
port = static_cast<uint16_t>(jPort);
}
+
PlatformConfig cfg{
JniUtils::getServiceType(env, jServiceType),
JniUtils::getModeType(env, jModeType),
JniUtils::getQOS(env, static_cast<int>(jQOS)),
JniOcSecurity::getOCPersistentStorage()
};
-
OCPlatform::Configure(cfg);
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
return nullptr;
}
JniOcResourceHandle* jniHandle = new JniOcResourceHandle(resourceHandle);
{
LOGE("%s", e.reason().c_str());
delete entityHandler;
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
return nullptr;
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("Error is due to %s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
return nullptr;
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
return nullptr;
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
catch (OCException& e)
{
LOGE("%s", e.reason().c_str());
- ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
}
}
/*
* Class: org_iotivity_base_OcRepresentation
+* Method: getHost
+* Signature: ()Ljava/lang/String;
+*/
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getHost
+(JNIEnv *env, jobject thiz)
+{
+ LOGD("OcRepresentation_getHost");
+ OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
+ if (!rep) return nullptr;
+
+ std::string uri(rep->getHost());
+ return env->NewStringUTF(uri.c_str());
+}
+
+/*
+* Class: org_iotivity_base_OcRepresentation
* Method: setUri
* Signature: (Ljava/lang/String;)V
*/
/*
* Class: org_iotivity_base_OcRepresentation
+ * Method: getHost
+ * Signature: ()Ljava/lang/String;
+ */
+ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getHost
+ (JNIEnv *, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcRepresentation
* Method: setUri
* Signature: (Ljava/lang/String;)V
*/
return m_sharedResource->observe(observeType, queryParametersMap, observeCallback, QoS);
}
-OCStackResult JniOcResource::cancelObserve(JNIEnv* env)
-{
- this->m_onObserveManager.removeAllListeners(env);
- return m_sharedResource->cancelObserve();
-}
-
OCStackResult JniOcResource::cancelObserve(JNIEnv* env, QualityOfService qos)
{
- //TODO confirm behavior
- //add removal of java listeners by qos
- this->m_onObserveManager.removeAllListeners(env);
+ if (QualityOfService::HighQos != qos)
+ {
+ this->m_onObserveManager.removeAllListeners(env);
+ }
return m_sharedResource->cancelObserve(qos);
}
/*
* Class: org_iotivity_base_OcResource
-* Method: cancelObserve
-* Signature: ()V
-*/
-JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve
-(JNIEnv *env, jobject thiz)
-{
- LOGD("OcResource_cancelObserve");
- JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
-
- try
- {
- OCStackResult result = resource->cancelObserve(env);
-
- if (OC_STACK_OK != result)
- {
- ThrowOcException(result, "OcResource_cancelObserve");
- }
- }
- catch (OCException& e)
- {
- LOGE("%s", e.reason().c_str());
- ThrowOcException(e.code(), e.reason().c_str());
- }
-}
-
-/*
-* Class: org_iotivity_base_OcResource
* Method: cancelObserve1
* Signature: I)V
*/
LOGD("OcResource_dispose");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
delete resource;
-}
\ No newline at end of file
+}
/*
* Class: org_iotivity_base_OcResource
- * Method: cancelObserve
- * Signature: ()V
- */
- JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve
- (JNIEnv *, jobject);
-
- /*
- * Class: org_iotivity_base_OcResource
* Method: cancelObserve1
* Signature: (I)V
*/
m_ownerResource->removeOnObserveListener(env, m_jwListener);
env->Throw((jthrowable)ex);
}
+
+ if (OC_OBSERVE_DEREGISTER == sequenceNumber)
+ {
+ checkExAndRemoveListener(env);
+ }
}
if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
public static final String PRESENCE_URI = "/oic/ad";
private static volatile boolean sIsPlatformInitialized = false;
+ private static QualityOfService sPlatformQualityOfService = QualityOfService.NA;
private OcPlatform() {
}
if (!sIsPlatformInitialized) {
CaInterface.initialize(platformConfig.getContext());
+ sPlatformQualityOfService = platformConfig.getQualityOfService();
+
OcPlatform.configure(
platformConfig.getServiceType().getValue(),
platformConfig.getModeType().getValue(),
/**
* This API registers a resource with the server
- * <P>
+ * <p/>
* Note: This API applies to server & client side.
* </P>
*
/**
* This API registers a resource with the server NOTE: This API applies to server side only.
- * <P>
+ * <p/>
* Note: This API applies to server side only.
* </P>
+ *
* @param resourceUri The URI of the resource. Example: "a/light"
* @param resourceTypeName The resource type. Example: "light"
* @param resourceInterface The resource interface (whether it is collection etc).
"OcPlatform.Configure before any other API calls are permitted");
}
}
+
+ /**
+ * Gets platform quality of service
+ *
+ * @return quality of service
+ */
+ public static QualityOfService getPlatformQualityOfService() {
+ OcPlatform.initCheck();
+ return sPlatformQualityOfService;
+ }
}
public native String getUri();
+ public native String getHost();
+
public native void setUri(String uri);
/**
*
* @throws OcException
*/
- public native void cancelObserve() throws OcException;
+ public void cancelObserve() throws OcException{
+ this.cancelObserve(OcPlatform.getPlatformQualityOfService());
+ }
/**
* Method to cancel the observation on the resource
######################################################################
# Common build options (release, target os, target arch)
######################################################################
-targets_disallow_multitransport = ['arduino', 'android']
+targets_disallow_multitransport = ['arduino']
help_vars = Variables()
help_vars.Add(BoolVariable('VERBOSE', 'Show compilation', False))
examples_env.AppendUnique(CPPPATH = [
'../../resource/include/',
'../../resource/csdk/stack/include',
- '../../resource/csdk/ocrandom/include',
+ '../../resource/c_common/ocrandom/include',
'../../resource/csdk/logger/include',
'../../resource/oc_logger/include'
])
YOCTOLDFLAGS=-loc -loctbstack -loc_logger -lmraa
-CXXFLAGS=-I../../resource/include -I../../resource/csdk/stack/include -I../../resource/csdk/ocrandom/include -I../../resource/csdk/logger/include -I../../resource/oc_logger/include
+CXXFLAGS=-I../../resource/include -I../../resource/csdk/stack/include -I../../resource/c_common/ocrandom/include -I../../resource/csdk/logger/include -I../../resource/oc_logger/include
LDFLAGS=-L../../out/linux/$(CLIENTARCH)/$(BUILDTYPE) -loc -loctbstack -loc_logger
--- /dev/null
+SUPPORTED CIPHER-SUITES
+ TLS_PSK_WITH_AES_128_CCM_8(0xC0A8)
+ TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8(0xC0AE)
+ TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256(0xC037)
+ TLS_ECDH_anon_WITH_AES_128_CBC_SHA256(0xC018)
+
+TEST APPLICATIONS
+These applications can be build from Iotivity's root directory using below commands:
+scons extlibs/tinydtls/dtls-client SECURED=1 RELEASE=0
+scons extlibs/tinydtls/dtls-server SECURED=1 RELEASE=0
+
+
+INTER-OPERABILITY TESTING
+tinyDTLS's cipher-suite implementations can be verified for compatibility against other
+SSL libraries.
+Use below commands to perform compatibility testing against mBed SSL library.
+./ssl_server2 debug_level=5 dtls=1 psk=73656372657450534b psk_identity=Client_identity \
+ force_version=dtls1_2 force_ciphersuite=TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256
+./dtls-client -v 6 -c 4 localhost 4433
+
+./ssl_client2 debug_level=5 dtls=1 psk=73656372657450534b psk_identity=Client_identity \
+ force_version=dtls1_2 force_ciphersuite=TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256
+./dtls-server -v 6 localhost -p 4433
+
+Above commands can also be tested with TLS-PSK-WITH-AES-128-CCM-8 cipher suite.
+
else:
env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-env.AppendUnique(CPPDEFINES = ['DTLSV12', 'WITH_SHA256', 'DTLS_CHECK_CONTENTTYPE'])
+env.AppendUnique(CPPDEFINES = ['DTLSV12', 'WITH_SHA256', 'DTLS_CHECK_CONTENTTYPE', 'SHA2_USE_INTTYPES_H'])
libtinydtls = env.StaticLibrary('libtinydtls', env.get('TINYDTLS_SRC'), OBJPREFIX='libtinydtls_')
static size_t
dtls_cbc_encrypt(aes128_t *aes_ctx,
- unsigned char *key, size_t keylen,
+ unsigned char *mac_key, size_t mac_keylen,
const unsigned char *iv,
const unsigned char *src, size_t srclen,
unsigned char *buf) {
dtls_hdr = src - DTLS_CBC_IV_LENGTH - sizeof(dtls_record_header_t);
//Calculate MAC : Append the MAC code to end of content
- hmac_ctx = dtls_hmac_new(key, keylen);
+ hmac_ctx = dtls_hmac_new(mac_key, mac_keylen);
dtls_mac(hmac_ctx,
dtls_hdr,
src, srclen,
static size_t
dtls_cbc_decrypt(aes128_t *aes_ctx,
- unsigned char *key, size_t keylen,
+ unsigned char *mac_key, size_t mac_keylen,
const unsigned char *iv,
const unsigned char *src, size_t srclen,
unsigned char *buf) {
int i, j;
int blocks;
int depaddinglen = 0;
+ uint8_t wrongpadding_flag = 0;
dtls_hmac_context_t* hmac_ctx = NULL;
pos = buf;
//de-padding
depaddinglen = buf[srclen -1];
+ /**
+ * message validation check in case of wrong key.
+ * In case of wrong padding legnth was detected
+ * set depadding length to zero in order to resist the padding oracle attack
+ * and prevent invalid memory access.
+ */
+ if(srclen <= DTLS_HMAC_DIGEST_SIZE + depaddinglen + 1) {
+ depaddinglen = 0;
+ wrongpadding_flag = 1;
+ }
+
//Calculate MAC
- hmac_ctx = dtls_hmac_new(key, keylen);
+ hmac_ctx = dtls_hmac_new(mac_key, mac_keylen);
if(!hmac_ctx) {
return -1;
}
//verify the MAC
if(memcmp(mac_buf,
buf + (srclen - DTLS_HMAC_DIGEST_SIZE - depaddinglen - 1),
- DTLS_HMAC_DIGEST_SIZE) != 0)
+ DTLS_HMAC_DIGEST_SIZE) != 0 || wrongpadding_flag)
{
dtls_crit("Failed to verification of MAC\n");
return -1;
dtls_encrypt(const unsigned char *src, size_t length,
unsigned char *buf,
unsigned char *nounce,
- unsigned char *key, size_t keylen,
+ unsigned char *write_key, size_t write_keylen,
+ unsigned char *mac_key, size_t mac_keylen,
const unsigned char *aad, size_t la,
const dtls_cipher_t cipher)
{
if(cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ||
cipher == TLS_PSK_WITH_AES_128_CCM_8) {
- ret = rijndael_set_key_enc_only(&ctx->data.ctx, key, 8 * keylen);
+ ret = rijndael_set_key_enc_only(&ctx->data.ctx, write_key, 8 * write_keylen);
if (ret < 0) {
/* cleanup everything in case the key has the wrong size */
dtls_warn("cannot set rijndael key\n");
}
if(cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 ||
cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256) {
- ret = rijndael_set_key(&ctx->data.ctx, key, 8 * keylen);
+ ret = rijndael_set_key(&ctx->data.ctx, write_key, 8 * write_keylen);
if (ret < 0) {
/* cleanup everything in case the key has the wrong size */
dtls_warn("cannot set rijndael key\n");
if (src != buf)
memmove(buf, src, length);
- ret = dtls_cbc_encrypt(&ctx->data, key, keylen, nounce, src, length, buf);
+ ret = dtls_cbc_encrypt(&ctx->data, mac_key, mac_keylen, nounce, src, length, buf);
}
error:
dtls_decrypt(const unsigned char *src, size_t length,
unsigned char *buf,
unsigned char *nounce,
- unsigned char *key, size_t keylen,
+ unsigned char *read_key, size_t read_keylen,
+ unsigned char *mac_key, size_t mac_keylen,
const unsigned char *aad, size_t la,
const dtls_cipher_t cipher)
{
if(cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ||
cipher == TLS_PSK_WITH_AES_128_CCM_8) {
- ret = rijndael_set_key_enc_only(&ctx->data.ctx, key, 8 * keylen);
+ ret = rijndael_set_key_enc_only(&ctx->data.ctx, read_key, 8 * read_keylen);
if (ret < 0) {
/* cleanup everything in case the key has the wrong size */
dtls_warn("cannot set rijndael key\n");
if(cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 ||
cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256) {
- ret = rijndael_set_key(&ctx->data.ctx, key, 8 * keylen);
+ ret = rijndael_set_key(&ctx->data.ctx, read_key, 8 * read_keylen);
if (ret < 0) {
/* cleanup everything in case the key has the wrong size */
dtls_warn("cannot set rijndael key\n");
if (src != buf)
memmove(buf, src, length);
- ret = dtls_cbc_decrypt(&ctx->data, key, keylen, nounce, src, length, buf);
+ ret = dtls_cbc_decrypt(&ctx->data, mac_key, mac_keylen, nounce, src, length, buf);
}
error:
#include "ecc/ecc.h"
/* TLS_PSK_WITH_AES_128_CCM_8 */
-#define DTLS_MAC_KEY_LENGTH 0
+#define DTLS_CCM_MAC_KEY_LENGTH 0 /* MAC Key length for AES-CCM cipher suites */
+#define DTLS_CBC_MAC_KEY_LENGTH 32 /* MAC Key length for AES-CBC Cipher suites */
#define DTLS_KEY_LENGTH 16 /* AES-128 */
#define DTLS_BLK_LENGTH 16 /* AES-128 */
#define DTLS_MAC_LENGTH DTLS_HMAC_DIGEST_SIZE
-#define DTLS_IV_LENGTH 4 /* length of nonce_explicit */
+#define DTLS_CCM_IV_LENGTH 4 /* length of nonce_explicit */
#define DTLS_CBC_IV_LENGTH 16
/**
* be large enough to hold the pre_master_secret, i.e. twice the length of the
* pre-shared key + 1.
*/
+#define CCM_KB_LENGTH \
+ (2 * DTLS_KEY_LENGTH + 2 * DTLS_CCM_IV_LENGTH)
+
+#define CBC_KB_LENGTH \
+ (2 * DTLS_CBC_MAC_KEY_LENGTH + 2 * DTLS_KEY_LENGTH )
+
#define MAX_KEYBLOCK_LENGTH \
- (2 * DTLS_MAC_KEY_LENGTH + 2 * DTLS_KEY_LENGTH + 2 * DTLS_IV_LENGTH)
+ ((CCM_KB_LENGTH) > (CBC_KB_LENGTH) ? (CCM_KB_LENGTH) : (CBC_KB_LENGTH) )
/** Length of DTLS master_secret */
#define DTLS_MASTER_SECRET_LENGTH 48
/* The following macros provide access to the components of the
* key_block in the security parameters. */
+static inline int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
+{
+ switch(cipher)
+ {
+ case TLS_NULL_WITH_NULL_NULL:
+
+ return 0;
+ break;
+
+ case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
+ case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
+
+ return DTLS_CBC_MAC_KEY_LENGTH;
+ break;
+
+ case TLS_PSK_WITH_AES_128_CCM_8:
+ case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
+
+ return DTLS_CCM_MAC_KEY_LENGTH;
+ break;
+ }
+
+ return -1;
+}
+
+
+static inline int dtls_kb_iv_size(dtls_cipher_t cipher)
+{
+ switch(cipher)
+ {
+ case TLS_NULL_WITH_NULL_NULL:
+ case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
+ case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
+
+ return 0;
+ break;
+
+ case TLS_PSK_WITH_AES_128_CCM_8:
+ case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
+
+ return DTLS_CCM_IV_LENGTH;
+ break;
+ }
+
+ return -1;
+}
+
+
+
+
#define dtls_kb_client_mac_secret(Param, Role) ((Param)->key_block)
#define dtls_kb_server_mac_secret(Param, Role) \
- (dtls_kb_client_mac_secret(Param, Role) + DTLS_MAC_KEY_LENGTH)
+ (dtls_kb_client_mac_secret(Param, Role) + dtls_kb_mac_secret_size((Param)->cipher))
#define dtls_kb_remote_mac_secret(Param, Role) \
((Role) == DTLS_SERVER \
? dtls_kb_client_mac_secret(Param, Role) \
((Role) == DTLS_CLIENT \
? dtls_kb_client_mac_secret(Param, Role) \
: dtls_kb_server_mac_secret(Param, Role))
-#define dtls_kb_mac_secret_size(Param, Role) DTLS_MAC_KEY_LENGTH
#define dtls_kb_client_write_key(Param, Role) \
- (dtls_kb_server_mac_secret(Param, Role) + DTLS_MAC_KEY_LENGTH)
+ (dtls_kb_server_mac_secret(Param, Role) + dtls_kb_mac_secret_size((Param)->cipher))
#define dtls_kb_server_write_key(Param, Role) \
(dtls_kb_client_write_key(Param, Role) + DTLS_KEY_LENGTH)
#define dtls_kb_remote_write_key(Param, Role) \
#define dtls_kb_client_iv(Param, Role) \
(dtls_kb_server_write_key(Param, Role) + DTLS_KEY_LENGTH)
#define dtls_kb_server_iv(Param, Role) \
- (dtls_kb_client_iv(Param, Role) + DTLS_IV_LENGTH)
+ (dtls_kb_client_iv(Param, Role) + dtls_kb_iv_size((Param)->cipher))
#define dtls_kb_remote_iv(Param, Role) \
((Role) == DTLS_SERVER \
? dtls_kb_client_iv(Param, Role) \
((Role) == DTLS_CLIENT \
? dtls_kb_client_iv(Param, Role) \
: dtls_kb_server_iv(Param, Role))
-#define dtls_kb_iv_size(Param, Role) DTLS_IV_LENGTH
#define dtls_kb_size(Param, Role) \
- (2 * (dtls_kb_mac_secret_size(Param, Role) + \
- dtls_kb_key_size(Param, Role) + dtls_kb_iv_size(Param, Role)))
+ (2 * (dtls_kb_mac_secret_size((Param)->cipher) + \
+ dtls_kb_key_size(Param, Role) + dtls_kb_iv_size((Param)->cipher)))
/* just for consistency */
#define dtls_kb_digest_size(Param, Role) DTLS_MAC_LENGTH
int dtls_encrypt(const unsigned char *src, size_t length,
unsigned char *buf,
unsigned char *nounce,
- unsigned char *key, size_t keylen,
+ unsigned char *write_key, size_t write_keylen,
+ unsigned char *mac_key, size_t mac_keylen,
const unsigned char *aad, size_t aad_length,
const dtls_cipher_t cipher);
int dtls_decrypt(const unsigned char *src, size_t length,
unsigned char *buf,
unsigned char *nounce,
- unsigned char *key, size_t keylen,
+ unsigned char *read_key, size_t read_keylen,
+ unsigned char *mac_key, size_t mac_keylen,
const unsigned char *a_data, size_t a_data_length,
const dtls_cipher_t cipher);
dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
dtls_debug_dump(" client_MAC_secret",
dtls_kb_client_mac_secret(config, peer->role),
- dtls_kb_mac_secret_size(config, peer->role));
+ dtls_kb_mac_secret_size(config->cipher));
dtls_debug_dump(" server_MAC_secret",
dtls_kb_server_mac_secret(config, peer->role),
- dtls_kb_mac_secret_size(config, peer->role));
+ dtls_kb_mac_secret_size(config->cipher));
dtls_debug_dump(" client_write_key",
dtls_kb_client_write_key(config, peer->role),
dtls_debug_dump(" client_IV",
dtls_kb_client_iv(config, peer->role),
- dtls_kb_iv_size(config, peer->role));
+ dtls_kb_iv_size(config->cipher));
dtls_debug_dump(" server_IV",
dtls_kb_server_iv(config, peer->role),
- dtls_kb_iv_size(config, peer->role));
+ dtls_kb_iv_size(config->cipher));
}
/** returns the name of the goven handshake type number.
/* create key_block from master_secret
* key_block = PRF(master_secret,
"key expansion" + tmp.random.server + tmp.random.client) */
+ security->cipher = handshake->cipher;
+ security->compression = handshake->compression;
+ security->rseq = 0;
dtls_prf(master_secret,
DTLS_MASTER_SECRET_LENGTH,
memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
dtls_debug_keyblock(security);
- security->cipher = handshake->cipher;
- security->compression = handshake->compression;
- security->rseq = 0;
return 0;
}
start + DTLS_CBC_IV_LENGTH, nonce,
dtls_kb_local_write_key(security, peer->role),
dtls_kb_key_size(security, peer->role),
+ dtls_kb_local_mac_secret(security, peer->role),
+ dtls_kb_mac_secret_size(security->cipher),
NULL, 0,
security->cipher);
if (res < 0)
memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
memcpy(nonce, dtls_kb_local_iv(security, peer->role),
- dtls_kb_iv_size(security, peer->role));
- memcpy(nonce + dtls_kb_iv_size(security, peer->role), start, 8); /* epoch + seq_num */
+ dtls_kb_iv_size(security->cipher));
+ memcpy(nonce + dtls_kb_iv_size(security->cipher), start, 8); /* epoch + seq_num */
dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
dtls_kb_local_write_key(security, peer->role),
dtls_kb_key_size(security, peer->role),
+ dtls_kb_local_mac_secret(security, peer->role),
+ dtls_kb_mac_secret_size(security->cipher),
A_DATA, A_DATA_LEN,
security->cipher);
uint8 cookie[], size_t cookie_length) {
uint8 buf[DTLS_CH_LENGTH_MAX];
uint8 *p = buf;
- uint8_t cipher_size;
- uint8_t extension_size;
+ uint8_t cipher_size = 0;
+ uint8_t extension_size = 0;
int psk = 0;
int ecdsa = 0;
int ecdh_anon = 0;
}
cipher_size = 2 + ((ecdsa || x509) ? 2 : 0) + (psk ? 2 : 0) + (ecdh_anon ? 2 : 0) + (ecdhe_psk ? 2 : 0);
- extension_size = (ecdsa || x509) ? (2 + 6 + 6 + 8 + 6) : 0;
+
+ /* Is extension needed? */
+ extension_size = (ecdsa || x509 || ecdhe_psk || ecdh_anon) ? 2 : 0;
+ /* Supported EC and Supported Point Formats */
+ extension_size += (ecdsa || x509 || ecdhe_psk | ecdh_anon) ? ( 8 + 6) : 0;
+ /* Supported Client and Server Cert Types */
+ extension_size += (ecdsa || x509) ? ( 6 + 6) : 0;
if (cipher_size == 0) {
dtls_crit("no cipher callbacks implemented\n");
p += sizeof(uint8);
- /* client certificate type extension */
+ /* server certificate type extension */
dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
p += sizeof(uint16);
dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
p += sizeof(uint8);
+ }
+ if (ecdsa || x509 || ecdhe_psk || ecdh_anon ) {
/* elliptic_curves */
dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
p += sizeof(uint16);
clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
dtls_kb_remote_write_key(security, peer->role),
dtls_kb_key_size(security, peer->role),
+ dtls_kb_remote_mac_secret(security, peer->role),
+ dtls_kb_mac_secret_size(security->cipher),
NULL, 0,
security->cipher);
memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
- dtls_kb_iv_size(security, peer->role));
+ dtls_kb_iv_size(security->cipher));
/* read epoch and seq_num from message */
- memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
+ memcpy(nonce + dtls_kb_iv_size(security->cipher), *cleartext, 8);
*cleartext += 8;
clen -= 8;
clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
dtls_kb_remote_write_key(security, peer->role),
dtls_kb_key_size(security, peer->role),
+ dtls_kb_remote_mac_secret(security, peer->role),
+ dtls_kb_mac_secret_size(security->cipher),
A_DATA, A_DATA_LEN,
security->cipher);
}
return psk_client_id_length;
case DTLS_PSK_KEY:
if (id_len != psk_server_id_length || memcmp(psk_server_id, id, id_len) != 0) {
- dtls_warn("PSK for unknown id requested, exiting\n");
- return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
- } else if (result_length < psk_key_length) {
+ dtls_debug("PSK for unknown id requested\n");
+ }
+ if (result_length < psk_key_length) {
dtls_warn("cannot set psk -- buffer too small\n");
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
Import('env')
import os
+target_os = env.get('TARGET_OS')
+
env.AppendUnique(CPPPATH = [
os.path.join(Dir('.').abspath),
os.path.join(Dir('.').abspath, 'oic_malloc/include'),
- os.path.join(Dir('.').abspath, 'oic_string/include')
+ os.path.join(Dir('.').abspath, 'oic_string/include'),
+ os.path.join(Dir('.').abspath, 'ocrandom/include')
])
-if env.get('TARGET_OS') == 'tizen':
+if target_os == 'tizen':
env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
else:
env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')])
-env.AppendUnique(LIBS = ['c_common'])
+if target_os in ['tizen', 'linux']:
+ env.ParseConfig("pkg-config --cflags --libs uuid")
+
+env.PrependUnique(LIBS = ['c_common'])
common_env = env.Clone()
# Source files and Targets
######################################################################
common_src = [
- 'oic_string/src/oic_string.c',
- 'oic_malloc/src/oic_malloc.c'
- ]
+ 'oic_string/src/oic_string.c',
+ 'oic_malloc/src/oic_malloc.c',
+ 'ocrandom/src/ocrandom.c',
+ ]
commonlib = common_env.StaticLibrary('c_common', common_src)
common_env.InstallTarget(commonlib, 'c_common')
#ifdef ARDUINO
#include "Arduino.h"
+// ARM GCC compiler doesnt define srandom function.
+#if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
+#define HAVE_SRANDOM 1
+#endif
+
uint8_t GetRandomBitRaw()
{
return analogRead((uint8_t)ANALOG_IN) & 0x1;
{
result += result + GetRandomBit();
}
- randomSeed(result);
+#if HAVE_SRANDOM
+ srandom(result);
+#else
+ srand(result);
+#endif
return 0;
#endif
#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
return rand() & 0x00FF;
#elif defined ARDUINO
- return random(256) & 0x00FF;
+#ifdef HAVE_SRANDOM
+ return random() & 0x00FF;
+#else
+ return rand() & 0x00FF;
+#endif
#endif
}
from tools.scons.RunTest import *
run_test(randomtest_env,
'resource_csdk_random_test.memcheck',
- 'resource/csdk/ocrandom/test/randomtests')
+ 'resource/c_common/ocrandom/test/randomtests')
'../../extlibs/cjson/',
'../../extlibs/timer/',
'logger/include',
- 'ocrandom/include',
'stack/include',
'stack/include/internal',
'../oc_logger/include',
liboctbstack_env.AppendUnique(LIBS = ['coap', 'm'])
-if target_os == 'tizen':
- liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
+if target_os in ['tizen', 'linux']:
+ liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
if target_os not in ['android', 'arduino', 'windows', 'winrt']:
liboctbstack_env.AppendUnique(LIBS = ['pthread'])
OCTBSTACK_SRC + 'occollection.c',
OCTBSTACK_SRC + 'oicgroup.c',
'logger/src/logger.c',
- 'ocrandom/src/ocrandom.c',
OCTBSTACK_SRC + "rdpayload.c"
]
env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER'])
if with_tcp == True:
- if target_os in['linux']:
+ if target_os in ['linux', 'tizen']:
env.AppendUnique(CPPDEFINES = ['TCP_ADAPTER'])
print "CA Transport is TCP"
else:
help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', False))
help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
-help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP', 'TCP']))
+help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP']))
help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
+help_vars.Add(BoolVariable('WITH_TCP', 'Enable TCP', False))
help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)
release_mode = env.get('RELEASE')
secured = env.get('SECURED')
logging = env.get('LOGGING')
+with_tcp = env.get('WITH_TCP')
print "Given Transport is %s" % transport
print "Given OS is %s" % target_os
if target_os == 'tizen':
- command = "sh resource/csdk/connectivity/build/tizen/gbsbuild.sh %s %s %s %s %s" % (transport, secured, buildsample, release_mode, logging)
+ command = "sh resource/csdk/connectivity/build/tizen/gbsbuild.sh %s %s %s %s %s %s" % (transport, secured, buildsample, release_mode, logging, with_tcp)
print "Created Command is %s" % command
gbs_script = env.Command('gbs_build', None, command)
AlwaysBuild ('gbs_script')
\ No newline at end of file
echo $5
export LOGGING=$5
+echo $6
+export WITH_TCP=$6
+
echo $TARGET_TRANSPORT
echo $BUILD_SAMPLE
+echo $WITH_TCP
rm -rf $name-$version
fi
echo "Calling core gbs build command"
-gbscommand="gbs build -A armv7l --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5'"
+gbscommand="gbs build -A armv7l --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'WITH_TCP $6'"
echo $gbscommand
if eval $gbscommand; then
echo "Core build is successful"
BuildRequires: boost-system
BuildRequires: boost-filesystem
BuildRequires: scons
+BuildRequires: pkgconfig(uuid)
%description
echo %{ROOTDIR}
scons TARGET_OS=tizen -c
-scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING}
+scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING} WITH_TCP=%{WITH_TCP}
%install
mkdir -p %{DEST_INC_DIR}
target_os = env.get('TARGET_OS')
transport = env.get('TARGET_TRANSPORT')
+with_tcp = env.get('WITH_TCP')
print "Given Transport is %s" % transport
else:
env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER'])
+ if with_tcp == True:
+ env.AppendUnique(CPPDEFINES = ['TCP_ADAPTER'])
+ print "CA Transport is TCP"
+ else:
+ env.AppendUnique(CPPDEFINES = ['NO_TCP_ADAPTER'])
+
env.SConscript(['../con/lib/libcoap-4.1.1/SConscript'])
env.SConscript(['../con/SConscript'])
#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
#else // These macros are defined for Linux, Android, and Arduino
#define OIC_LOG_INIT() OICLogInit()
-#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
- OICLogBuffer((level), (tag), (buffer), (bufferSize))
#ifdef ARDUINO
#define OIC_LOG_CONFIG(ctx)
#define OIC_LOG_V(level, tag, ...)
// To enable OIC_LOG_V, uncomment the below
//#define OIC_LOG_V(level, tag, format, ...) OICLogv((level), PCF(tag), __LINE__, PCF(format), __VA_ARGS__)
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
+ OICLogBuffer((level), PCF(tag), (buffer), (bufferSize))
#else
#define OIC_LOG_CONFIG(ctx) OICLogConfig((ctx))
#define OIC_LOG_SHUTDOWN() OICLogShutdown()
#define OIC_LOG(level, tag, logStr) OICLog((level), (tag), (logStr))
#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__)
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
+ OICLogBuffer((level), tag, (buffer), (bufferSize))
#endif //ARDUINO
#endif //__TIZEN__
#else //TB_LOG
#ifdef __cplusplus
}
#endif // __cplusplus
-#endif /* U_LOGGER_H_ */
\ No newline at end of file
+#endif /* U_LOGGER_H_ */
return NULL;
}
+ // check the method type of request info.
+ // Keep this check in sync with CAMethod_t
+ switch (rep->method)
+ {
+ case CA_GET:
+ case CA_POST:
+ case CA_PUT:
+ case CA_DELETE:
+ break;
+ default:
+ OIC_LOG_V(ERROR, TAG, "Method %u is invalid", rep->method);
+ return NULL;
+ }
+
// allocate the request info structure.
CARequestInfo_t *clone = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
if (!clone)
(*linklist)->size -= 1;
}
+
+ OICFree(*linklist);
*linklist=NULL;
return CA_STATUS_OK;
*/
void CAClearServerInfoList(u_arraylist_t *serverInfoList);
+#ifndef WITH_ARDUINO
/**
* Convert address from binary to string.
- * @param[in] ipaddr IP address info.
- * @param[out] host address string (must be CA_IPADDR_SIZE).
- * @param[out] port host order port number.
+ * @param[in] sockAddr IP address info.
+ * @param[in] sockAddrLen size of sockAddr.
+ * @param[out] host address string (must be CA_IPADDR_SIZE).
+ * @param[out] port host order port number.
*/
-void CAConvertAddrToName(const struct sockaddr_storage *sockaddr, char *host, uint16_t *port);
+void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, socklen_t sockAddrLen,
+ char *host, uint16_t *port);
/**
* Convert address from string to binary.
* @param[out] ipaddr IP address info.
*/
void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storage *sockaddr);
+#endif /* WITH_ARDUINO */
#ifdef __ANDROID__
/**
const CABlockDataID_t *blockID, coap_list_t **options);
/**
- * Add the block option in pdu data.
- * @param[in] pdu pdu object.
+ * Add the block option in option list.
* @param[out] block block data.
* @param[in] blockType block option type.
+ * @param[out] options option list.
* @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
*/
-CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t blockType,
+CAResult_t CAAddBlockOptionImpl(coap_block_t *block, uint8_t blockType,
coap_list_t **options);
/**
+ * Add the option list in pdu data.
+ * @param[out] pdu pdu object.
+ * @param[out] options option list.
+ * @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAAddOptionToPDU(coap_pdu_t *pdu, coap_list_t **options);
+
+/**
* Add the size option in pdu data.
* @param[in/out] pdu pdu object.
* @param[in] sizeType size option type.
libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
'-fdata-sections', '-fno-exceptions'])
-if target_os == 'linux':
+if target_os in ['linux', 'tizen']:
if with_tcp == True:
libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
unsigned int length_field_data = 0;
switch(transport)
{
+ case coap_tcp:
+ length = header[0] >> 4;
+ break;
case coap_tcp_8bit:
length = header[1] + COAP_TCP_LENGTH_FIELD_8_BIT;
break;
#ifdef WORDS_BIGENDIAN
typedef union
{
- typedef struct
+ struct
{
unsigned int version:2; /* protocol version */
unsigned int type:2; /* type flag */
CAResponseInfo_t responseInfo = { 0 };
- if (msgType != CA_MSG_RESET)
+ if (CA_MSG_RESET == msgType ||
+ (CA_MSG_ACKNOWLEDGE == msgType && CA_EMPTY == responseValue))
+ {
+ printf("RESET or ACK/EMPTY. there will be not payload/option\n");
+ responseInfo.result = CA_EMPTY;
+ }
+ else
{
responseData.token = g_clientToken;
responseData.tokenLength = g_clientTokenLength;
{
uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
responseData.payload = (CAPayload_t) malloc(length);
- sprintf((char *) responseData.payload, SECURE_INFO_DATA, g_resourceUri,
- g_localSecurePort);
+ snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
+ g_resourceUri, g_localSecurePort);
responseData.payloadSize = length;
}
else
{
uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
responseData.payload = (CAPayload_t) malloc(length);
- sprintf((char *) responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
+ snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, g_resourceUri);
responseData.payloadSize = length;
}
}
- //msgType is RESET
- else
- {
- responseInfo.result = CA_EMPTY;
- }
responseInfo.info = responseData;
// destroy remote endpoint
CADestroyEndpoint(g_clientEndpoint);
g_clientEndpoint = NULL;
+ free(responseData.payload);
}
JNIEXPORT void JNICALL
free(requestData.resourceUri);
return;
}
- snprintf((char *) requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
+ snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
+ resourceURI, g_localSecurePort);
requestData.payloadSize = length;
}
else
{
char networkInfo[NETWORK_INFO_LENGTH];
LOGI("Type: %d", tempInfo[index].adapter);
- sprintf(networkInfo, "%d",tempInfo[index].adapter);
+ snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].adapter);
callback("Type :", networkInfo);
if (CA_ADAPTER_IP == tempInfo[index].adapter)
{
LOGI("Port: %d", tempInfo[index].port);
- sprintf(networkInfo, "%d",tempInfo[index].port);
+ snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].port);
callback("Port: ", networkInfo);
}
LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
free(g_remoteAddress);
char portInfo[PORT_LENGTH] = { 0, };
- sprintf(portInfo, "%d", object->port);
+ snprintf(portInfo, PORT_LENGTH, "%d", object->port);
callback("Remote Port: ", portInfo);
//clone g_clientEndpoint
if (NULL != g_responseListenerObject)
{
char optionInfo[OPTION_INFO_LENGTH] = { 0, };
- sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
- requestInfo->info.options[i].optionID,
- requestInfo->info.options[i].optionLength);
+ snprintf(optionInfo, OPTION_INFO_LENGTH,
+ "Num[%d] - ID : %d, Option Length : %d", i + 1,
+ requestInfo->info.options[i].optionID,
+ requestInfo->info.options[i].optionLength);
callback("Option info: ", optionInfo);
free(g_remoteAddress);
char portInfo[PORT_LENGTH] = { 0, };
- sprintf(portInfo, "%d", object->port);
+ snprintf(portInfo, PORT_LENGTH, "%d", object->port);
callback("Remote Port: ", portInfo);
if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
if (NULL != g_responseListenerObject)
{
char optionInfo[OPTION_INFO_LENGTH] = { 0, };
- sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
- responseInfo->info.options[i].optionID,
- responseInfo->info.options[i].optionLength);
+ snprintf(optionInfo, OPTION_INFO_LENGTH,
+ "Num[%d] - ID : %d, Option Length : %d", i + 1,
+ responseInfo->info.options[i].optionID,
+ responseInfo->info.options[i].optionLength);
callback("Option info: ", optionInfo);
// Get file length
fseek(file, 0, SEEK_END);
fileLen = ftell(file);
+ if (-1 == fileLen)
+ {
+ fprintf(stderr, "Failed to read file length");
+ fclose(file);
+ return false;
+ }
fseek(file, 0, SEEK_SET);
LOGI("file size: %d", fileLen);
char* path = calloc(1, sizeof(char) * path_length);
if (path != NULL)
{
- sprintf(path, RECEIVED_FILE_PATH, day, timeString);
+ snprintf(path, path_length, RECEIVED_FILE_PATH, day, timeString);
LOGI("received file path: %s", path);
FILE *fp = fopen(path, "wt");
}
printf("Data: %s\n", requestInfo->info.payload);
printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
+ printf("Resource URI: %s \n", requestInfo->info.resourceUri);
if (requestInfo->info.options)
{
printf("Data: %s\n", responseInfo->info.payload);
printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
printf("Token: %s\n", responseInfo->info.token);
+ printf("Resource URI: %s \n", responseInfo->info.resourceUri);
+
if (responseInfo->info.options)
{
uint32_t len = responseInfo->info.numOptions;
.payloadSize = 0,
.resourceUri = resourceUri };
- if(CA_MSG_RESET != messageType)
+ if (CA_MSG_RESET == messageType ||
+ (CA_MSG_ACKNOWLEDGE == messageType && CA_EMPTY == responseCode))
+ {
+ printf("RESET or ACK/EMPTY. there will be not payload/option\n");
+
+ }
+ else
{
responseData.token = (info != NULL) ? info->token : NULL;
responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
// Get file length
fseek(file, 0, SEEK_END);
fileLen = ftell(file);
+ if (-1 == fileLen)
+ {
+ fprintf(stderr, "Failed to get file length\n");
+ fclose(file);
+ return false;
+ }
fseek(file, 0, SEEK_SET);
// Allocate memory
#define COAPS_PREFIX "coaps://"
#define COAPS_PREFIX_LEN 8
+#define COAP_TCP_PREFIX "coap+tcp://"
+#define COAP_TCP_PREFIX_LEN 11
+
// Iotivity Device Identity.
const unsigned char IDENTITY[] = ("1111111111111111");
printf("Enter the URI like below....\n");
printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
+ printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
}
else
{
printf("IP : 0\n");
printf("GATT : 1\n");
printf("RFCOMM : 2\n");
+ printf("TCP : 4\n");
printf("select : ");
char buf[MAX_BUF_LEN] = { 0 };
int number = buf[0] - '0';
- if (number < 0 || number > 3)
+ if (number < 0 || number > 4)
{
printf("Invalid network type\n");
return;
printf("IP : 0\n");
printf("GATT : 1\n");
printf("RFCOMM : 2\n");
+ printf("TCP : 4\n");
printf("select : ");
char buf[MAX_BUF_LEN] = { 0 };
int number = buf[0] - '0';
- if (number < 0 || number > 3)
+ if (number < 0 || number > 4)
{
printf("Invalid network type\n");
return;
printf("IP : 0\n");
printf("GATT : 1\n");
printf("RFCOMM : 2\n");
+ printf("TCP : 4\n");
printf("select : ");
char buf[MAX_BUF_LEN] = { 0 };
}
int number = buf[0] - '0';
- if (0 > number || 2 < number)
+ if (0 > number || 4 < number)
{
printf("\nInvalid Network type");
return CA_NOT_SUPPORTED;
startIndex = COAP_PREFIX_LEN;
*flags = CA_IPV4;
}
+ else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
+ {
+ printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
+ startIndex = COAP_TCP_PREFIX_LEN;
+ *flags = CA_IPV4;
+ }
// #2. copy uri for parse
int32_t len = strlen(uri) - startIndex;
if 'ALL' in ca_transport:
transports = [ 'ip_adapter', 'bt_edr_adapter', 'bt_le_adapter']
- if ca_os == 'linux':
- if with_tcp:
- transports.append ('tcp_adapter')
if with_ra:
transports.append ('ra_adapter')
env.SConscript(dirs = [
if 'BLE' in ca_transport:
env.SConscript(os.path.join(ca_path, 'bt_le_adapter/SConscript'))
+if ca_os in ['linux', 'tizen']:
+ if with_tcp == True:
+ env.SConscript(os.path.join(ca_path, 'tcp_adapter/SConscript'))
print "Include path is %s" % env.get('CPPPATH')
print "Files path is %s" % env.get('CA_SRC')
((addrInfo->addr.st.ss_family == AF_INET) ? CA_IPV4 : CA_IPV6) | CA_SECURE, .port = 0 },
.identity =
{ 0 } };
- CAConvertAddrToName(&(addrInfo->addr.st), sep.endpoint.addr, &sep.endpoint.port);
+ CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, sep.endpoint.addr, &sep.endpoint.port);
if (NULL == g_caDtlsContext)
{
CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
- CAConvertAddrToName(&(addrInfo->addr.st), endpoint.addr, &endpoint.port);
+ CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, endpoint.addr, &endpoint.port);
endpoint.flags = addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
endpoint.flags |= CA_SECURE;
endpoint.adapter = CA_ADAPTER_IP;
stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
uint16_t port = 0;
- CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
+ CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, peerAddr, &port);
CARemovePeerFromPeerInfoList(peerAddr, port);
}
stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
uint16_t port = 0;
- CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
+ CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, peerAddr, &port);
if(CA_STATUS_OK != CAAddIdToPeerInfoList(peerAddr, port, desc, descLen) )
{
stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
uint16_t port = 0;
- CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
+ CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, peerAddr, &port);
CAResult_t result = CAAddIdToPeerInfoList(peerAddr, port,
crtChain[0].subject.data + DER_SUBJECT_HEADER_LEN + 2, crtChain[0].subject.data[DER_SUBJECT_HEADER_LEN + 1]);
* These two conversion functions return void because errors can't happen
* (because of NI_NUMERIC), and there's nothing to do if they do happen.
*/
-void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, char *host, uint16_t *port)
+void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, socklen_t sockAddrLen,
+ char *host, uint16_t *port)
{
VERIFY_NON_NULL_VOID(sockAddr, CA_ADAPTER_UTILS_TAG, "sockAddr is null");
VERIFY_NON_NULL_VOID(host, CA_ADAPTER_UTILS_TAG, "host is null");
VERIFY_NON_NULL_VOID(port, CA_ADAPTER_UTILS_TAG, "port is null");
int r = getnameinfo((struct sockaddr *)sockAddr,
- sizeof (struct sockaddr_storage),
+ sockAddrLen,
host, MAX_ADDR_STR_SIZE_CA,
NULL, 0,
NI_NUMERICHOST|NI_NUMERICSERV);
if (EAI_SYSTEM == r)
{
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
- "getaddrinfo failed: errno %s", strerror(errno));
+ "getnameinfo failed: errno %s", strerror(errno));
}
else
{
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
- "getaddrinfo failed: %s", gai_strerror(r));
+ "getnameinfo failed: %s", gai_strerror(r));
}
return;
}
VERIFY_NON_NULL(options, TAG, "options");
// get set block data from CABlock list-set.
- coap_block_t *block1 = CAGetBlockOption(blockID,
- COAP_OPTION_BLOCK1);
- coap_block_t *block2 = CAGetBlockOption(blockID,
- COAP_OPTION_BLOCK2);
+ coap_block_t *block1 = CAGetBlockOption(blockID, COAP_OPTION_BLOCK1);
+ coap_block_t *block2 = CAGetBlockOption(blockID, COAP_OPTION_BLOCK2);
if (!block1 || !block2)
{
OIC_LOG(ERROR, TAG, "getting has failed");
(CA_MSG_NONCONFIRM == (*pdu)->hdr->coap_hdr_udp_t.type &&
CA_GET != (*pdu)->hdr->coap_hdr_udp_t.code))
{
- int32_t res = coap_write_block_opt(block2, COAP_OPTION_BLOCK2, *pdu, dataLength);
- switch (res)
- {
- case -2: /* illegal block */
- code = COAP_RESPONSE_CODE(CA_BAD_REQ);
- OIC_LOG(ERROR, TAG, "write block option : -2");
- goto error;
- case -1: /* should really not happen */
- OIC_LOG(ERROR, TAG, "write block option : -1");
- break;
- case -3: /* cannot handle request */
- code = COAP_RESPONSE_CODE(CA_INTERNAL_SERVER_ERROR);
- OIC_LOG(ERROR, TAG, "write block option : -3");
- goto error;
- default:
- OIC_LOG(INFO, TAG, "success write block option");
- }
+ CAGetMoreBitFromBlock(dataLength, block2);
CALogBlockInfo(block2);
// if block number is 0, add size2 option
if (0 == block2->num)
{
- res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength, options);
+ CAResult_t res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
}
}
+ CAResult_t res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "add has failed");
+ CARemoveBlockDataFromList(blockID);
+ return res;
+ }
+
if (block1->num)
{
OIC_LOG(DEBUG, TAG, "combining block1 and block2");
- CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
+ res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
block1->num = 0;
}
+ res = CAAddOptionToPDU(*pdu, options);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "add has failed");
+ CARemoveBlockDataFromList(blockID);
+ return res;
+ }
+
if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
block2->num, block2->szx))
{
else
{
OIC_LOG(DEBUG, TAG, "option2, not ACK msg");
- CAResult_t res = CAAddBlockOptionImpl(*pdu, block2, COAP_OPTION_BLOCK2, options);
+ CAResult_t res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "add has failed");
+ CARemoveBlockDataFromList(blockID);
+ return res;
+ }
+
+ res = CAAddOptionToPDU(*pdu, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
if (CA_MSG_ACKNOWLEDGE == (*pdu)->hdr->coap_hdr_udp_t.type)
{
OIC_LOG(DEBUG, TAG, "option1 and ACK msg..");
- CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
+ CAResult_t res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "add has failed");
+ CARemoveBlockDataFromList(blockID);
+ return res;
+ }
+
+ res = CAAddOptionToPDU(*pdu, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
}
}
- res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
+ res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
CARemoveBlockDataFromList(blockID);
return res;
}
+
+ res = CAAddOptionToPDU(*pdu, options);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "add has failed");
+ CARemoveBlockDataFromList(blockID);
+ return res;
+ }
+
CALogBlockInfo(block1);
if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
return CA_STATUS_OK;
}
-CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t blockType,
+CAResult_t CAAddBlockOptionImpl(coap_block_t *block, uint8_t blockType,
coap_list_t **options)
{
OIC_LOG(DEBUG, TAG, "IN-AddBlockOptionImpl");
- VERIFY_NON_NULL(pdu, TAG, "pdu");
VERIFY_NON_NULL(block, TAG, "block");
VERIFY_NON_NULL(options, TAG, "options");
return CA_STATUS_INVALID_PARAM;
}
+ OIC_LOG(DEBUG, TAG, "OUT-AddBlockOptionImpl");
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAAddOptionToPDU(coap_pdu_t *pdu, coap_list_t **options)
+{
// after adding the block option to option list, add option list to pdu.
if (*options)
{
COAP_OPTION_DATA(*(coap_option *) opt->data));
OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
- coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
- COAP_OPTION_LENGTH(*(coap_option *) opt->data),
- COAP_OPTION_DATA(*(coap_option *) opt->data), coap_udp);
+ int ret = coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+ COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+ COAP_OPTION_DATA(*(coap_option *) opt->data), coap_udp);
+ if (!ret)
+ {
+ return CA_STATUS_FAILED;
+ }
}
}
OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
- OIC_LOG(DEBUG, TAG, "OUT-AddBlockOptionImpl");
return CA_STATUS_OK;
}
if (!g_isInitialized)
{
+ if (0 != OCSeedRandom())
+ {
+ OIC_LOG(ERROR, TAG, "Seed Random Failed");
+ }
+
CAResult_t res = CAInitializeMessageHandler();
if (res != CA_STATUS_OK)
{
}
g_isInitialized = true;
}
+
return CA_STATUS_OK;
}
{
for (uint32_t i = 0; i < info->numOptions; i++)
{
- OIC_LOG_V(DEBUG, TAG, "optionID: %d", info->options[i].optionID);
+ OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
}
OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
info->tokenLength);
}
- OIC_LOG_V(DEBUG, TAG, "msgID: %d", info->messageId);
+ OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
}
else
{
// For glibc information on feature test macros,
// Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
//
-// This file requires #define use due to random() and srandom()
// For details on compatibility and glibc support,
// Refer http://www.gnu.org/software/libc/manual/html_node/BSD-Random.html
#define _DEFAULT_SOURCE
#include "logger.h"
#include "oic_malloc.h"
#include "oic_string.h"
-
-// ARM GCC compiler doesnt define srandom function.
-#if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
-#define HAVE_SRANDOM 1
-#endif
+#include "ocrandom.h"
#define TAG "CA_PRTCL_MSG"
static const char COAP_URI_HEADER[] = "coap://[::]/";
-static unsigned int SEED = 0;
-
CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
CARequestInfo_t *outReqInfo)
{
// and ACKNOWLEDGE can use empty message when code is empty.
if (CA_MSG_RESET == info->type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info->type))
{
+ if ((CA_EMPTY == code) && (info->payloadSize > 0 || info->payload
+ || info->token || info->tokenLength > 0))
+ {
+ OIC_LOG(ERROR, TAG, "Empty message has unnecessary data after messageID");
+ return NULL;
+ }
+
OIC_LOG(DEBUG, TAG, "code is empty");
if (!(pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, NULL, transport)))
{
}
else
{
- if (CA_MSG_ACKNOWLEDGE != info->type && info->resourceUri)
+ if (info->resourceUri)
{
uint32_t length = strlen(info->resourceUri);
if (CA_MAX_URI_LENGTH < length)
return CA_STATUS_INVALID_PARAM;
}
- if (SEED == 0)
- {
-#ifdef ARDUINO
- SEED = now();
-#else
- SEED = time(NULL);
-#endif
- if (SEED == (unsigned int)((time_t)-1))
- {
- OIC_LOG(ERROR, TAG, "seed is not made");
- SEED = 0;
- return CA_STATUS_FAILED;
- }
-#if HAVE_SRANDOM
- srandom(SEED);
-#else
- srand(SEED);
-#endif
- }
-
// memory allocation
char *temp = (char *) OICCalloc(tokenLength, sizeof(char));
if (NULL == temp)
return CA_MEMORY_ALLOC_FAILED;
}
- // set random byte
- for (uint8_t index = 0; index < tokenLength; index++)
- {
- // use valid characters
-#ifdef ARDUINO
- temp[index] = rand() & 0x00FF;
-#else
- temp[index] = random() & 0x00FF;
-#endif
- }
+ OCFillRandomMem((uint8_t *)temp, tokenLength);
// save token
*token = temp;
{
(void)data;
OIC_LOG(DEBUG, TAG, "IN");
-
while (!caglobals.ip.terminate)
{
CAFindReadyMessage();
CAHandleNetlink();
break;
}
- else
+ else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
{
+ char buf[10];
+ (void)read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
CAInterface_t *ifchanged = CAFindInterfaceChange();
if (ifchanged)
{
}
break;
}
+ else
+ {
+ break;
+ }
(void)CAReceiveMessage(fd, flags);
FD_CLR(fd, readFds);
}
}
- CAConvertAddrToName(&srcAddr, sep.endpoint.addr, &sep.endpoint.port);
+ CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
if (flags & CA_SECURE)
{
# Source files to build common for all platforms
common_files = None
-if target_os == 'linux':
+if target_os in ['linux', 'tizen']:
common_files = [
os.path.join(src_dir, 'catcpadapter.c'),
os.path.join(src_dir, 'catcpserver.c') ]
}
svritem->u4tcp.fd = sockfd;
- CAConvertAddrToName((struct sockaddr_storage *)&clientaddr,
+ CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
(char *) &svritem->addr, &svritem->u4tcp.port);
ca_mutex_lock(g_mutexObjectList);
INPUT = . \
../stack/include \
../ocsocket/include \
- ../ocrandom/include \
+ ../../c_common/ocrandom/include \
../occoap/include \
# This tag can be used to specify the character encoding of the source files
os.path.join(Dir('.').abspath, './../stack/include/internal'),
os.path.join(Dir('.').abspath, './../logger'),
os.path.join(Dir('.').abspath, './../../oc_logger/include'),
- os.path.join(Dir('.').abspath, './../ocrandom/include'),
+ os.path.join(Dir('.').abspath, './../../c_common/ocrandom/include'),
os.path.join(Dir('.').abspath, './../connectivity/api'),
os.path.join(Dir('.').abspath, './../connectivity/common/inc'),
os.path.join(Dir('.').abspath, './../security/include'),
while (NULL != iterTable)
{
RTMGatewayEntry_t *entry = u_linklist_get_data(iterTable);
- if (NULL == entry && NULL == entry->destination)
+ if (NULL == entry || NULL == entry->destination)
{
OC_LOG(ERROR, TAG, "entry is NULL");
return false;
RM_NULL_CHECK_VOID(index, TAG, "index");
for (uint32_t i = 0; i < numOptions; i++)
{
- OC_LOG_V(DEBUG, TAG, "Request- optionID: %d", options[i].optionID);
+ OC_LOG_V(DEBUG, TAG, "Request- optionID: %u", options[i].optionID);
if (RM_OPTION_MESSAGE_SWITCHING == options[i].optionID)
{
OC_LOG_V(INFO, TAG, "Found Option at %d", i);
'../../../extlibs/cjson/',
'../../../extlibs/tinydtls/',
'../logger/include',
- '../ocrandom/include',
+ '../../c_common/ocrandom/include',
'../stack/include',
'../stack/include/internal',
'../../oc_logger/include',
*/
OCStackResult RemoveCredential(const OicUuid_t* credId);
+/**
+ * Remove all credential data on credential resource and persistent storage
+ *
+ * @retval
+ * OC_STACK_OK - no errors
+ * OC_STACK_ERROR - stack process error
+ */
+OCStackResult RemoveAllCredentials(void);
+
#if defined(__WITH_DTLS__)
/**
* This internal callback is used by lower stack (i.e. CA layer) to
provisioning_env.AppendUnique(CPPPATH = [
'../../stack/include',
'../../stack/include/internal',
- '../../ocrandom/include',
+ '../../../c_common/ocrandom/include',
'../../logger/include',
'../../../oc_logger/include',
'../../ocmalloc/include',
######################################################################
provisioning_env.AppendUnique(CPPPATH = [
'../../../../stack/include',
- '../../../../ocrandom/include',
+ '../../../../../c_common/ocrandom/include',
'../../../../logger/include',
'../../../../security/include',
'../../../../../oc_logger/include',
switch(connType & CT_MASK_ADAPTER)
{
case CT_ADAPTER_IP:
- switch(connType & CT_MASK_FLAGS)
+ switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)
{
case CT_IP_USE_V4:
snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
DeleteDoxmBinData(ptrDoxm);
return OC_STACK_KEEP_TRANSACTION;
}
-
+ char rsrc_uri[MAX_URI_LENGTH+1] = {0};
+ int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",
+ OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
+ if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri))
+ {
+ OC_LOG(ERROR, TAG, "rsrc_uri_string_print failed");
+ return OC_STACK_ERROR;
+ }
//Try to the unicast discovery to getting secure port
- char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
+ char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
if(!PMGenerateQuery(false,
clientResponse->devAddr.addr, clientResponse->devAddr.port,
clientResponse->connType,
- query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
+ query, sizeof(query), rsrc_uri))
{
OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
return OC_STACK_KEEP_TRANSACTION;
//Verifying if the ID of the sender is an AMS service that this device trusts.
if(resPayload &&
- memcmp(context->amsMgrContext->amsDeviceId.id, resPayload->sid,
+ memcmp(context->amsMgrContext->amsDeviceId.id,
+ ((OCDiscoveryPayload*)clientResponse->payload)->sid,
+ // resPayload->sid,
sizeof(context->amsMgrContext->amsDeviceId.id)) != 0)
{
context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
return 0;
}
+/**
+ * Get the default value
+ * @retval NULL for now. Update it when we finalize the default info.
+ */
+static OicSecCred_t* GetCredDefault()
+{
+ return NULL;
+}
/**
* This function adds the new cred to the credential list.
}
+/**
+ * Remove all credential data on credential resource and persistent storage
+ *
+ * @retval
+ * OC_STACK_OK - no errors
+ * OC_STACK_ERROR - stack process error
+ */
+OCStackResult RemoveAllCredentials(void)
+{
+ DeleteCredList(gCred);
+ gCred = GetCredDefault();
+
+ if(!UpdatePersistentStorage(gCred))
+ {
+ return OC_STACK_ERROR;
+ }
+ return OC_STACK_OK;
+}
+
static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
{
OCEntityHandlerResult ret = OC_EH_ERROR;
}
/**
- * Get the default value
- * @retval NULL for now. Update it when we finalize the default info.
- */
-static OicSecCred_t* GetCredDefault()
-{
- return NULL;
-}
-
-/**
* Initialize Cred resource by loading data from persistent storage.
*
* @retval
bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
+/**
+ * This function allocates memory for the byte string and sets it in the payload.
+ *
+ * @param payload Pointer to the payload to which byte string needs to be added.
+ * @param name Name of the byte string.
+ * @param value Byte string and it's length.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value);
+
+/**
+ * This function sets the byte string in the payload.
+ *
+ * @param payload Pointer to the payload to which byte string needs to be added.
+ * @param name Name of the byte string.
+ * @param value Byte string and it's length.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name,
+ OCByteString* value);
+
+/**
+ * This function gets the byte string from the payload.
+ *
+ * @param payload Pointer to the payload from which byte string needs to be retrieved.
+ * @param name Name of the byte string.
+ * @param value Byte string and it's length.
+ *
+ * @note: Caller needs to invoke OCFree on value.bytes after it is finished using the byte string.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name,
+ OCByteString* value);
+
bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, char** value);
OCRepPayload* value);
bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
+/**
+ * This function allocates memory for the byte string array and sets it in the payload.
+ *
+ * @param payload Pointer to the payload to which byte string array needs to be added.
+ * @param name Name of the byte string.
+ * @param array Byte string array.
+ * @param dimensions Number of byte strings in above array.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
+ OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+/**
+ * This function sets the byte string array in the payload.
+ *
+ * @param payload Pointer to the payload to which byte string array needs to be added.
+ * @param name Name of the byte string.
+ * @param array Byte string array.
+ * @param dimensions Number of byte strings in above array.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
+ const OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+/**
+ * This function gets the byte string array from the payload.
+ *
+ * @param payload Pointer to the payload from which byte string array needs to be retrieved.
+ * @param name Name of the byte string array.
+ * @param value Byte string array.
+ * @param dimensions Number of byte strings in above array.
+ *
+ * @note: Caller needs to invoke OICFree on 'bytes' field of all array elements after it is
+ * finished using the byte string array.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
+ OCByteString** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
// Device Payload
-OCDevicePayload* OCDevicePayloadCreate(const char* uri, const uint8_t* sid, const char* dname,
+OCDevicePayload* OCDevicePayloadCreate(const uint8_t* sid, const char* dname,
const char* specVer, const char* dmVer);
void OCDevicePayloadDestroy(OCDevicePayload* payload);
// Platform Payload
-OCPlatformPayload* OCPlatformPayloadCreate(const char* uri, const OCPlatformInfo* platformInfo);
-OCPlatformPayload* OCPlatformPayloadCreateAsOwner(char* uri, OCPlatformInfo* platformInfo);
+OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
+OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
/** To represent resource type with presence.*/
#define OC_RSRVD_RESOURCE_TYPE_PRESENCE "oic.wk.ad"
+/** To represent resource type with device.*/
+#define OC_RSRVD_RESOURCE_TYPE_DEVICE "oic.wk.d"
+
+/** To represent resource type with platform.*/
+#define OC_RSRVD_RESOURCE_TYPE_PLATFORM "oic.wk.p"
+
/** To represent interface.*/
#define OC_RSRVD_INTERFACE "if"
/** To represent default interface.*/
#define OC_RSRVD_INTERFACE_DEFAULT "oic.if.baseline"
+/** To represent read-only interface.*/
+#define OC_RSRVD_INTERFACE_READ "oic.if.r"
+
/** To represent ll interface.*/
#define OC_RSRVD_INTERFACE_LL "oic.if.ll"
#define OC_RSRVD_DATA_MODEL_VERSION "dmv"
/** Device specification version.*/
-#define OC_SPEC_VERSION "0.9.0"
+#define OC_SPEC_VERSION "core.1.0.0"
/** Device Data Model version.*/
-#define OC_DATA_MODEL_VERSION "sec.0.95"
+#define OC_DATA_MODEL_VERSION "res.1.0.0"
/**
* These provide backward compatibility - their use is deprecated.
/**Remote Access over XMPP.*/
OC_ADAPTER_REMOTE_ACCESS = (1 << 3),
#endif
-
-#ifdef TCP_ADAPTER
/** CoAP over TCP.*/
OC_ADAPTER_TCP = (1 << 4)
-#endif
} OCTransportAdapter;
/** Remote Access over XMPP.*/
CT_ADAPTER_REMOTE_ACCESS = (1 << 19),
#endif
-
-#ifdef TCP_ADAPTER
/** CoAP over TCP.*/
CT_ADAPTER_TCP = (1 << 20),
-#endif
/** Insecure transport is the default (subject to change).*/
OCREP_PROP_DOUBLE,
OCREP_PROP_BOOL,
OCREP_PROP_STRING,
+ OCREP_PROP_BYTE_STRING,
OCREP_PROP_OBJECT,
OCREP_PROP_ARRAY
}OCRepPayloadPropType;
+/** This structure will be used to represent a binary string for CBOR payloads.*/
+typedef struct
+{
+ /** pointer to data bytes.*/
+ uint8_t* bytes;
+
+ /** number of data bytes.*/
+ size_t len;
+} OCByteString;
+
#define MAX_REP_ARRAY_DEPTH 3
typedef struct
{
double* dArray;
bool* bArray;
char** strArray;
+
+ /** pointer to ByteString array.*/
+ OCByteString* ocByteStrArray;
+
struct OCRepPayload** objArray;
};
} OCRepPayloadValueArray;
double d;
bool b;
char* str;
+
+ /** ByteString object.*/
+ OCByteString ocByteStr;
+
struct OCRepPayload* obj;
OCRepPayloadValueArray arr;
};
typedef struct OCResourcePayload
{
char* uri;
- uint8_t* sid;
OCStringLL* types;
OCStringLL* interfaces;
uint8_t bitmap;
typedef struct
{
OCPayload base;
+
+ uint8_t* sid;
+
/** This structure holds the old /oic/res response. */
OCResourcePayload *resources;
/** This structure holds the collection response for the /oic/res. */
typedef struct
{
OCPayload base;
- char* uri;
uint8_t* sid;
char* deviceName;
char* specVersion;
OC_LOG(level, PL_TAG, "\tNO Resources");
return;
}
-
+ OC_LOG(level, PL_TAG, "\tSID:");
+ OC_LOG_BUFFER(level, PL_TAG, payload->sid, UUID_SIZE);
OCResourcePayload* res = payload->resources;
while(res)
{
OC_LOG_V(level, PL_TAG, "\tResource #%d", i);
OC_LOG_V(level, PL_TAG, "\tURI:%s", res->uri);
- OC_LOG(level, PL_TAG, "\tSID:");
- OC_LOG_BUFFER(level, PL_TAG, res->sid, UUID_SIZE);
OC_LOG(level, PL_TAG, "\tResource Types:");
OCStringLL* strll = res->types;
while(strll)
static inline void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
{
OC_LOG(level, PL_TAG, "Payload Type: Device");
- OC_LOG_V(level, PL_TAG, "\tURI:%s", payload->uri);
OC_LOG(level, PL_TAG, "\tSID:");
OC_LOG_BUFFER(level, PL_TAG, payload->sid, UUID_SIZE);
OC_LOG_V(level, PL_TAG, "\tDevice Name:%s", payload->deviceName);
void collectUniqueResource(const OCClientResponse * clientResponse)
{
- OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+ OCDiscoveryPayload* pay = (OCDiscoveryPayload*) clientResponse->payload;
+ OCResourcePayload* res = pay->resources;
+
+ // Including the NUL terminator, length of UUID string of the form:
+ // "a62389f7-afde-00b6-cd3e-12b97d2fcf09"
+# define UUID_LENGTH 37
+
char sidStr[UUID_LENGTH];
while(res) {
int ret = snprintf(sidStr, UUID_LENGTH,
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
- res->sid[0], res->sid[1], res->sid[2], res->sid[3],
- res->sid[4], res->sid[5], res->sid[6], res->sid[7],
- res->sid[8], res->sid[9], res->sid[10], res->sid[11],
- res->sid[12], res->sid[13], res->sid[14], res->sid[15]
+ pay->sid[0], pay->sid[1], pay->sid[2], pay->sid[3],
+ pay->sid[4], pay->sid[5], pay->sid[6], pay->sid[7],
+ pay->sid[8], pay->sid[9], pay->sid[10], pay->sid[11],
+ pay->sid[12], pay->sid[13], pay->sid[14], pay->sid[15]
);
if (ret == UUID_LENGTH - 1)
{
OICFree(val->str);
}
+ else if(val->type == OCREP_PROP_BYTE_STRING)
+ {
+ OICFree(val->ocByteStr.bytes);
+ }
else if (val->type == OCREP_PROP_OBJECT)
{
OCRepPayloadDestroy(val->obj);
}
OICFree(val->arr.strArray);
break;
+ case OCREP_PROP_BYTE_STRING:
+ for (size_t i = 0; i< dimTotal; ++i)
+ {
+ OICFree(val->arr.ocByteStrArray[i].bytes);
+ }
+ OICFree(val->arr.ocByteStrArray);
+ break;
case OCREP_PROP_OBJECT:
for(size_t i = 0; i< dimTotal;++i)
{
case OCREP_PROP_STRING:
val->str = (char*)value;
return val->str != NULL;
+ case OCREP_PROP_BYTE_STRING:
+ val->ocByteStr = *(OCByteString*)value;
+ break;
case OCREP_PROP_NULL:
return val != NULL;
case OCREP_PROP_ARRAY:
return *value != NULL;
}
+bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value)
+{
+ if (!value.bytes || !value.len)
+ {
+ return false;
+ }
+
+ OCByteString ocByteStr = {
+ .bytes = (uint8_t*)OICMalloc(value.len * sizeof(uint8_t)),
+ .len = value.len };
+
+ if(!ocByteStr.bytes)
+ {
+ return false;
+ }
+ memcpy(ocByteStr.bytes, value.bytes, ocByteStr.len);
+
+ bool b = OCRepPayloadSetPropByteStringAsOwner(payload, name, &ocByteStr);
+
+ if(!b)
+ {
+ OICFree(ocByteStr.bytes);
+ }
+ return b;
+}
+
+bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name, OCByteString* value)
+{
+ return OCRepPayloadSetProp(payload, name, value, OCREP_PROP_BYTE_STRING);
+}
+
+bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name, OCByteString* value)
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if (!val || val->type != OCREP_PROP_BYTE_STRING)
+ {
+ return false;
+ }
+
+ if (!value)
+ {
+ return false;
+ }
+
+ value->bytes = (uint8_t*)OICMalloc(val->ocByteStr.len * sizeof(uint8_t));
+ if (!value->bytes)
+ {
+ return false;
+ }
+ value->len = val->ocByteStr.len;
+ memcpy(value->bytes, val->ocByteStr.bytes, value->len);
+
+ return true;
+}
+
bool OCRepPayloadSetPropBool(OCRepPayload* payload,
const char* name, bool value)
{
return total;
}
+
+bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
+ OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
+
+ if (!val)
+ {
+ return false;
+ }
+
+ val->arr.type = OCREP_PROP_BYTE_STRING;
+ memcpy(val->arr.dimensions, dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ val->arr.ocByteStrArray = array;
+
+ return true;
+}
+
+bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
+ const OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ if (!array)
+ {
+ return NULL;
+ }
+
+ size_t dimTotal = calcDimTotal(dimensions);
+ if (dimTotal == 0)
+ {
+ return false;
+ }
+
+ OCByteString* newArray = (OCByteString*)OICCalloc(dimTotal, sizeof(OCByteString));
+
+ if (!newArray)
+ {
+ return false;
+ }
+
+ for (size_t i = 0; i < dimTotal; ++i)
+ {
+ newArray[i].bytes = (uint8_t*)OICMalloc(array[i].len * sizeof(uint8_t));
+ if (NULL == newArray[i].bytes)
+ {
+ for (size_t j = 0; j < i; ++j)
+ {
+ OICFree(newArray[j].bytes);
+ }
+
+ OICFree(newArray);
+ return false;
+ }
+ newArray[i].len = array[i].len;
+ memcpy(newArray[i].bytes, array[i].bytes, newArray[i].len);
+ }
+
+ bool b = OCRepPayloadSetByteStringArrayAsOwner(payload, name, newArray, dimensions);
+ if (!b)
+ {
+ for (size_t i = 0; i < dimTotal; ++i)
+ {
+ OICFree(newArray[i].bytes);
+ }
+
+ OICFree(newArray);
+ }
+ return b;
+}
+
+bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
+ OCByteString** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+ OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+ if (!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_BYTE_STRING
+ || !val->arr.ocByteStrArray)
+ {
+ return false;
+ }
+
+ size_t dimTotal = calcDimTotal(val->arr.dimensions);
+ if (dimTotal == 0)
+ {
+ return false;
+ }
+
+ *array = (OCByteString*)OICCalloc(dimTotal, sizeof(OCByteString));
+ if (!*array)
+ {
+ return false;
+ }
+
+ for (size_t i = 0; i < dimTotal; ++i)
+ {
+ OCByteString* tmp = &(*array)[i];
+ tmp->bytes = (uint8_t*)OICMalloc(val->arr.ocByteStrArray[i].len * sizeof(uint8_t));
+ if (NULL == tmp->bytes)
+ {
+ for (size_t j = 0; j < i; ++j)
+ {
+ OCByteString* tmp = &(*array)[j];
+ OICFree(tmp->bytes);
+ }
+ OICFree(*array);
+ *array = NULL;
+
+ return false;
+ }
+ tmp->len = val->arr.ocByteStrArray[i].len;
+ memcpy(tmp->bytes, val->arr.ocByteStrArray[i].bytes, tmp->len);
+ }
+
+ memcpy(dimensions, val->arr.dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+ return true;
+}
+
+
bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
{
}
pl->uri = OICStrdup(res->uri);
- pl->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
- if(!pl->uri || ! pl->sid)
+
+ if(!pl->uri)
{
FreeOCDiscoveryResource(pl);
return NULL;
}
- memcpy(pl->sid, OCGetServerInstanceID(), UUID_SIZE);
// types
OCResourceType* typePtr = res->rsrcType;
}
OICFree(payload->uri);
- OICFree(payload->sid);
OCFreeOCStringLL(payload->types);
OCFreeOCStringLL(payload->interfaces);
FreeOCDiscoveryResource(payload->next);
{
return;
}
-
+ OICFree(payload->sid);
FreeOCDiscoveryResource(payload->resources);
OICFree(payload);
}
-OCDevicePayload* OCDevicePayloadCreate(const char* uri, const uint8_t* sid, const char* dname,
+OCDevicePayload* OCDevicePayloadCreate(const uint8_t* sid, const char* dname,
const char* specVer, const char* dmVer)
{
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);
return;
}
- OICFree(payload->uri);
OICFree(payload->sid);
OICFree(payload->deviceName);
OICFree(payload->specVersion);
target->info.systemTime = OICStrdup(platformInfo->systemTime);
}
-OCPlatformPayload* OCPlatformPayloadCreateAsOwner(char* uri, OCPlatformInfo* platformInfo)
+OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo)
{
OCPlatformPayload* payload = (OCPlatformPayload*)OICCalloc(1, sizeof(OCPlatformPayload));
if(!payload)
}
payload->base.type = PAYLOAD_TYPE_PLATFORM;
- payload->uri = uri;
payload->info = *platformInfo;
return payload;
}
-OCPlatformPayload* OCPlatformPayloadCreate(const char* uri, const OCPlatformInfo* platformInfo)
+OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo)
{
OCPlatformPayload* payload = (OCPlatformPayload*)OICCalloc(1, sizeof(OCPlatformPayload));
}
payload->base.type = PAYLOAD_TYPE_PLATFORM;
- payload->uri = OICStrdup(uri);
OCCopyPlatformInfo(platformInfo, payload);
return payload;
static int64_t OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t* outPayload,
size_t* size);
static int64_t OCConvertRepPayload(OCRepPayload* payload, uint8_t* outPayload, size_t* size);
+static int64_t OCConvertRepMap(CborEncoder *map, const OCRepPayload* payload);
static int64_t OCConvertPresencePayload(OCPresencePayload* payload, uint8_t* outPayload,
size_t* size);
static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* outPayload,
cbor_encoder_init(&encoder, outPayload, *size, 0);
- CborEncoder rootArray;
- err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
CborEncoder map;
- err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+ err = err | cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
if(payload->securityData)
{
- err = err | AddTextStringToMap(&map, OC_RSRVD_REPRESENTATION,
- sizeof(OC_RSRVD_REPRESENTATION) - 1,
- payload->securityData);
+ err = err | cbor_encode_text_string(&map, payload->securityData,
+ strlen(payload->securityData));
}
- err = err | cbor_encoder_close_container(&rootArray, &map);
-
- err = err | cbor_encoder_close_container(&encoder, &rootArray);
+ err = err | cbor_encoder_close_container(&encoder, &map);
return checkError(err, &encoder, outPayload, size);
}
}
else if (payload->resources)
{
+ /*
+ The format for the payload is "modelled" as JSON.
+
+ [ // rootArray
+ { // rootMap
+ "di" : UUID, // device ID
+ links :[ // linksArray contains maps of resources
+ {
+ href, rt, if, policy // Resource 1
+ },
+ {
+ href, rt, if, policy // Resource 2
+ },
+ .
+ .
+ .
+ ]
+ }
+ ]
+ */
+ CborEncoder rootMap = {};
size_t resourceCount = OCDiscoveryPayloadGetResourceCount(payload);
- err = err | cbor_encoder_create_array(&encoder, &rootArray, resourceCount);
+
+ // Open the main root array
+ err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
+
+ // Open the root map in the root array
+ err = err | cbor_encoder_create_map(&rootArray, &rootMap, DISCOVERY_CBOR_RES_MAP_LEN);
+
+ // Insert Device ID into the root map
+ err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_DEVICE_ID,
+ sizeof(OC_RSRVD_DEVICE_ID) - 1);
+ err = err | cbor_encode_byte_string(&rootMap, payload->sid, UUID_SIZE);
+
+
+ // Insert Links into the root map.
+ CborEncoder linkArray = {};
+ err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_LINKS,
+ sizeof(OC_RSRVD_LINKS) - 1);
+ err = err | cbor_encoder_create_array(&rootMap, &linkArray, resourceCount);
for(size_t i = 0; i < resourceCount; ++i)
{
- CborEncoder map;
+ CborEncoder resourceMapElement = {};
OCResourcePayload* resource = OCDiscoveryPayloadGetResource(payload, i);
if(!resource)
{
return OC_STACK_INVALID_PARAM;
}
- err = err | cbor_encoder_create_map(&rootArray, &map, DISCOVERY_CBOR_RES_MAP_LEN);
+ // resource map inside the links array.
+ err = err | cbor_encoder_create_map(&linkArray, &resourceMapElement,
+ DISCOVERY_CBOR_LINKS_MAP_LEN);
+
+ // Below are insertions of the resource properties into the map.
+ // Uri
+ err = err | AddTextStringToMap(&resourceMapElement, OC_RSRVD_HREF,
+ sizeof(OC_RSRVD_HREF) - 1,
+ resource->uri);
+ // Resource Type
+ if (resource->types)
+ {
+ char* joinedTypes = OCStringLLJoin(resource->types);
+ if (joinedTypes)
+ {
+ err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_RESOURCE_TYPE,
+ sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
+ err = err | cbor_encode_text_string(&resourceMapElement, joinedTypes,
+ strlen(joinedTypes));
+ OICFree(joinedTypes);
+ }
+ else
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+ // Interface Types
+ if (resource->interfaces)
+ {
+ char* joinedInterfaces = OCStringLLJoin(resource->interfaces);
+ if (joinedInterfaces)
+ {
+ err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_INTERFACE,
+ sizeof(OC_RSRVD_INTERFACE) - 1);
+ err = err | cbor_encode_text_string(&resourceMapElement, joinedInterfaces,
+ strlen(joinedInterfaces));
+ OICFree(joinedInterfaces);
+ }
+ else
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+
+ // Policy
+ CborEncoder policyMap;
+ err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_POLICY,
+ sizeof(OC_RSRVD_POLICY) - 1);
+ err = err | cbor_encoder_create_map(&resourceMapElement, &policyMap, CborIndefiniteLength);
- // Device ID
- err = err | cbor_encode_text_string(&map, OC_RSRVD_DEVICE_ID,
- sizeof(OC_RSRVD_DEVICE_ID) - 1);
- err = err | cbor_encode_byte_string(&map, resource->sid, UUID_SIZE);
+ // Bitmap
+ err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
+ sizeof(OC_RSRVD_BITMAP) - 1);
+ err = err | cbor_encode_uint(&policyMap, resource->bitmap);
+ if(resource->secure)
{
- CborEncoder linkArray;
- err = err | cbor_encode_text_string(&map, OC_RSRVD_LINKS, sizeof(OC_RSRVD_LINKS) -1);
- err = err | cbor_encoder_create_array(&map, &linkArray, CborIndefiniteLength);
+ err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
+ sizeof(OC_RSRVD_SECURE) - 1);
+ err = err | cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
- // Link Map
+ if(resource->port != 0)
{
- CborEncoder linkMap;
- err = err | cbor_encoder_create_map(&linkArray, &linkMap, DISCOVERY_CBOR_LINKS_MAP_LEN);
-
- // Uri
- err = err | AddTextStringToMap(&linkMap, OC_RSRVD_HREF,
- sizeof(OC_RSRVD_HREF) - 1,
- resource->uri);
- // Resource Type
- if (resource->types)
- {
- char* joinedTypes = OCStringLLJoin(resource->types);
- if (joinedTypes)
- {
- err = err | cbor_encode_text_string(&linkMap, OC_RSRVD_RESOURCE_TYPE,
- sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
- err = err | cbor_encode_text_string(&linkMap, joinedTypes,
- strlen(joinedTypes));
- OICFree(joinedTypes);
- }
- else
- {
- return OC_STACK_NO_MEMORY;
- }
- }
- // Interface Types
- if (resource->interfaces)
- {
- char* joinedInterfaces = OCStringLLJoin(resource->interfaces);
- if (joinedInterfaces)
- {
- err = err | cbor_encode_text_string(&linkMap, OC_RSRVD_INTERFACE,
- sizeof(OC_RSRVD_INTERFACE) - 1);
- err = err | cbor_encode_text_string(&linkMap, joinedInterfaces,
- strlen(joinedInterfaces));
- OICFree(joinedInterfaces);
- }
- else
- {
- return OC_STACK_NO_MEMORY;
- }
- }
- // Policy
- {
- CborEncoder policyMap;
- err = err | cbor_encode_text_string(&linkMap, OC_RSRVD_POLICY,
- sizeof(OC_RSRVD_POLICY) - 1);
- err = err | cbor_encoder_create_map(&linkMap, &policyMap, CborIndefiniteLength);
-
- // Bitmap
- err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
- sizeof(OC_RSRVD_BITMAP) - 1);
- err = err | cbor_encode_uint(&policyMap, resource->bitmap);
-
- if(resource->secure)
- {
- err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
- sizeof(OC_RSRVD_SECURE) - 1);
- err = err | cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
-
- if(resource->port != 0)
- {
- err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
- sizeof(OC_RSRVD_HOSTING_PORT) - 1);
- err = err | cbor_encode_uint(&policyMap, resource->port);
- }
- }
-
- err = err | cbor_encoder_close_container(&linkMap, &policyMap);
- }
- // Close
- err = err | cbor_encoder_close_container(&linkArray, &linkMap);
+ err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
+ sizeof(OC_RSRVD_HOSTING_PORT) - 1);
+ err = err | cbor_encode_uint(&policyMap, resource->port);
}
- err = err | cbor_encoder_close_container(&map, &linkArray);
}
- err = err | cbor_encoder_close_container(&rootArray, &map);
+
+ err = err | cbor_encoder_close_container(&resourceMapElement, &policyMap);
+
+ // Finsihed encoding a resource, close the map.
+ err = err | cbor_encoder_close_container(&linkArray, &resourceMapElement);
}
- // Close main array
+ // Close links array inside the root map.
+ err = err | cbor_encoder_close_container(&rootMap, &linkArray);
+ // close root map inside the root array.
+ err = err | cbor_encoder_close_container(&rootArray, &rootMap);
+ // Close the final root array.
err = err | cbor_encoder_close_container(&encoder, &rootArray);
}
int64_t err = 0;
cbor_encoder_init(&encoder, outPayload, *size, 0);
- CborEncoder rootArray;
- err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
+ CborEncoder repMap;
+ err = err | cbor_encoder_create_map(&encoder, &repMap, CborIndefiniteLength);
- {
- CborEncoder map;
- err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+ // Device ID
+ err = err | cbor_encode_text_string(&repMap, OC_RSRVD_DEVICE_ID,
+ sizeof(OC_RSRVD_DEVICE_ID) - 1);
+ err = err | cbor_encode_byte_string(&repMap, payload->sid, UUID_SIZE);
- // uri
- err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
- payload->uri);
+ // Device Name
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
+ sizeof(OC_RSRVD_DEVICE_NAME) - 1,
+ payload->deviceName);
- // Rep Map
- {
- CborEncoder repMap;
- err = err | cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
- sizeof(OC_RSRVD_REPRESENTATION) - 1);
- err = err | cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
-
- // Device ID
- err = err | cbor_encode_text_string(&repMap, OC_RSRVD_DEVICE_ID,
- sizeof(OC_RSRVD_DEVICE_ID) - 1);
- err = err | cbor_encode_byte_string(&repMap, payload->sid, UUID_SIZE);
-
- // Device Name
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
- sizeof(OC_RSRVD_DEVICE_NAME) - 1,
- payload->deviceName);
-
- // Device Spec Version
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
- sizeof(OC_RSRVD_SPEC_VERSION) - 1,
- payload->specVersion);
-
- // Device data Model Version
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
- sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1,
- payload->dataModelVersion);
-
- err = err | cbor_encoder_close_container(&map, &repMap);
- }
+ // Device Spec Version
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
+ sizeof(OC_RSRVD_SPEC_VERSION) - 1,
+ payload->specVersion);
- // Close Map
- err = err | cbor_encoder_close_container(&rootArray, &map);
- }
+ // Device data Model Version
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
+ sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1,
+ payload->dataModelVersion);
- // Close main array
- err = err | cbor_encoder_close_container(&encoder, &rootArray);
+ err = err | cbor_encoder_close_container(&encoder, &repMap);
return checkError(err, &encoder, outPayload, size);
}
int64_t err = 0;
cbor_encoder_init(&encoder, outPayload, *size, 0);
- CborEncoder rootArray;
- err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
{
- CborEncoder map;
- err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
-
- // uri
- err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
- payload->uri);
-
- // Rep Map
- {
- CborEncoder repMap;
- err = err | cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
- sizeof(OC_RSRVD_REPRESENTATION) - 1);
- err = err | cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
-
- // Platform ID
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
- sizeof(OC_RSRVD_PLATFORM_ID) - 1,
- payload->info.platformID);
-
- // MFG Name
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
- sizeof(OC_RSRVD_MFG_NAME) - 1,
- payload->info.manufacturerName);
-
- // MFG Url
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
- sizeof(OC_RSRVD_MFG_URL) - 1,
- payload->info.manufacturerUrl);
-
- // Model Num
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
- sizeof(OC_RSRVD_MODEL_NUM) - 1,
- payload->info.modelNumber);
-
- // Date of Mfg
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
- sizeof(OC_RSRVD_MFG_DATE) - 1,
- payload->info.dateOfManufacture);
-
- // Platform Version
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
- sizeof(OC_RSRVD_PLATFORM_VERSION) - 1,
- payload->info.platformVersion);
-
- // OS Version
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
- sizeof(OC_RSRVD_OS_VERSION) - 1,
- payload->info.operatingSystemVersion);
-
- // Hardware Version
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
- sizeof(OC_RSRVD_HARDWARE_VERSION) - 1,
- payload->info.hardwareVersion);
-
- // Firmware Version
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
- sizeof(OC_RSRVD_FIRMWARE_VERSION) - 1,
- payload->info.firmwareVersion);
-
- // Support URL
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
- sizeof(OC_RSRVD_SUPPORT_URL) - 1,
- payload->info.supportUrl);
-
- // System Time
- err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
- sizeof(OC_RSRVD_SYSTEM_TIME) - 1,
- payload->info.systemTime);
- err = err | cbor_encoder_close_container(&map, &repMap);
- }
+ CborEncoder repMap;
+ err = err | cbor_encoder_create_map(&encoder, &repMap, CborIndefiniteLength);
+
+ // Platform ID
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
+ sizeof(OC_RSRVD_PLATFORM_ID) - 1,
+ payload->info.platformID);
+
+ // MFG Name
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
+ sizeof(OC_RSRVD_MFG_NAME) - 1,
+ payload->info.manufacturerName);
+
+ // MFG Url
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
+ sizeof(OC_RSRVD_MFG_URL) - 1,
+ payload->info.manufacturerUrl);
+
+ // Model Num
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
+ sizeof(OC_RSRVD_MODEL_NUM) - 1,
+ payload->info.modelNumber);
+
+ // Date of Mfg
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
+ sizeof(OC_RSRVD_MFG_DATE) - 1,
+ payload->info.dateOfManufacture);
+
+ // Platform Version
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
+ sizeof(OC_RSRVD_PLATFORM_VERSION) - 1,
+ payload->info.platformVersion);
+
+ // OS Version
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
+ sizeof(OC_RSRVD_OS_VERSION) - 1,
+ payload->info.operatingSystemVersion);
+
+ // Hardware Version
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
+ sizeof(OC_RSRVD_HARDWARE_VERSION) - 1,
+ payload->info.hardwareVersion);
+
+ // Firmware Version
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
+ sizeof(OC_RSRVD_FIRMWARE_VERSION) - 1,
+ payload->info.firmwareVersion);
+
+ // Support URL
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
+ sizeof(OC_RSRVD_SUPPORT_URL) - 1,
+ payload->info.supportUrl);
+
+ // System Time
+ err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
+ sizeof(OC_RSRVD_SYSTEM_TIME) - 1,
+ payload->info.systemTime);
// Close Map
- err = err | cbor_encoder_close_container(&rootArray, &map);
+ err = err | cbor_encoder_close_container(&encoder, &repMap);
}
- // Close main array
- err = err | cbor_encoder_close_container(&encoder, &rootArray);
-
return checkError(err, &encoder, outPayload, size);
}
}
else
{
- err = OCConvertSingleRepPayload(array, valArray->objArray[index]);
+ err = OCConvertRepMap(array, valArray->objArray[index]);
}
break;
case OCREP_PROP_ARRAY:
return err;
}
-static int64_t OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload)
+static int64_t OCConvertRepMap(CborEncoder *map, const OCRepPayload* payload)
{
int64_t err = 0;
- CborEncoder map;
- err = err | cbor_encoder_create_map(parent, &map, CborIndefiniteLength);
-
- // Uri
- err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF,
- sizeof(OC_RSRVD_HREF) - 1,
- payload->uri);
-
- // Prop Map
- // resource types, interfaces
- if(payload->types || payload->interfaces)
- {
- OC_LOG(INFO, TAG, "Payload has types or interfaces");
- err = err | cbor_encode_text_string(&map,
- OC_RSRVD_PROPERTY,
- sizeof(OC_RSRVD_PROPERTY) - 1);
- CborEncoder propMap;
- err = err | cbor_encoder_create_map(&map, &propMap, 2);
-
- if (payload->types)
- {
- char* joinedTypes = OCStringLLJoin(payload->types);
- if (joinedTypes)
- {
- err = err | cbor_encode_text_string(&propMap, OC_RSRVD_RESOURCE_TYPE,
- sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
- err = err | cbor_encode_text_string(&propMap, joinedTypes,
- strlen(joinedTypes));
- OICFree(joinedTypes);
- }
- else
- {
- return OC_STACK_NO_MEMORY;
- }
- }
- if (payload->interfaces)
- {
- char* joinedInterfaces = OCStringLLJoin(payload->interfaces);
- if (joinedInterfaces)
- {
- err = err | cbor_encode_text_string(&propMap, OC_RSRVD_INTERFACE,
- sizeof(OC_RSRVD_INTERFACE) - 1);
- err = err | cbor_encode_text_string(&propMap, joinedInterfaces,
- strlen(joinedInterfaces));
- OICFree(joinedInterfaces);
- }
- else
- {
- return OC_STACK_NO_MEMORY;
- }
- }
- err = err | cbor_encoder_close_container(&map, &propMap);
- }
+ CborEncoder repMap;
+ err = err | cbor_encoder_create_map(map, &repMap, CborIndefiniteLength);
+ err = err | OCConvertSingleRepPayload(&repMap, payload);
+ err = err | cbor_encoder_close_container(map, &repMap);
+ return err;
+}
- // Rep Map
+static int64_t OCConvertSingleRepPayload(CborEncoder* repMap, const OCRepPayload* payload)
+{
+ int64_t err = 0;
+ OCRepPayloadValue* value = payload->values;
+ while(value)
{
- CborEncoder repMap;
- err = err | cbor_encode_text_string(&map,
- OC_RSRVD_REPRESENTATION,
- sizeof(OC_RSRVD_REPRESENTATION) - 1);
- err = err | cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
- OCRepPayloadValue* value = payload->values;
- while(value)
+ err = err | cbor_encode_text_string(repMap,
+ value->name,
+ strlen(value->name));
+ switch(value->type)
{
- err = err | cbor_encode_text_string(&repMap,
- value->name,
- strlen(value->name));
- switch(value->type)
- {
- case OCREP_PROP_NULL:
- err = err | cbor_encode_null(&repMap);
- break;
- case OCREP_PROP_INT:
- err = err | cbor_encode_int(&repMap,
- value->i);
- break;
- case OCREP_PROP_DOUBLE:
- err = err | cbor_encode_double(&repMap,
- value->d);
- break;
- case OCREP_PROP_BOOL:
- err = err | cbor_encode_boolean(&repMap,
- value->b);
- break;
- case OCREP_PROP_STRING:
- err = err | cbor_encode_text_string(&repMap,
- value->str, strlen(value->str));
- break;
- case OCREP_PROP_OBJECT:
- err = err | OCConvertSingleRepPayload(&repMap, value->obj);
- break;
- case OCREP_PROP_ARRAY:
- err = err | OCConvertArray(&repMap, &value->arr);
- break;
- default:
- OC_LOG_V(ERROR, TAG, "Invalid Prop type: %d",
- value->type);
- break;
- }
- value = value->next;
+ case OCREP_PROP_NULL:
+ err = err | cbor_encode_null(repMap);
+ break;
+ case OCREP_PROP_INT:
+ err = err | cbor_encode_int(repMap,
+ value->i);
+ break;
+ case OCREP_PROP_DOUBLE:
+ err = err | cbor_encode_double(repMap,
+ value->d);
+ break;
+ case OCREP_PROP_BOOL:
+ err = err | cbor_encode_boolean(repMap,
+ value->b);
+ break;
+ case OCREP_PROP_STRING:
+ err = err | cbor_encode_text_string(repMap,
+ value->str, strlen(value->str));
+ break;
+ case OCREP_PROP_BYTE_STRING:
+ err = err | cbor_encode_byte_string(repMap,
+ value->ocByteStr.bytes, value->ocByteStr.len);
+ break;
+ case OCREP_PROP_OBJECT:
+ err = err | OCConvertRepMap(repMap, value->obj);
+ break;
+ case OCREP_PROP_ARRAY:
+ err = err | OCConvertArray(repMap, &value->arr);
+ break;
+ default:
+ OC_LOG_V(ERROR, TAG, "Invalid Prop type: %d",
+ value->type);
+ break;
}
-
- err = err | cbor_encoder_close_container(&map, &repMap);
+ value = value->next;
}
- // Close Map
- err = err | cbor_encoder_close_container(parent, &map);
-
return err;
}
int64_t err = 0;
cbor_encoder_init(&encoder, outPayload, *size, 0);
- CborEncoder rootArray;
- err = err | cbor_encoder_create_array(&encoder, &rootArray, CborIndefiniteLength);
+ CborEncoder rootMap;
+ err = err | cbor_encoder_create_map(&encoder, &rootMap, CborIndefiniteLength);
+
+ if (payload->types)
+ {
+ OC_LOG(INFO, TAG, "Payload has types or interfaces");
+ char* joinedTypes = OCStringLLJoin(payload->types);
+ if (joinedTypes)
+ {
+ err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_RESOURCE_TYPE,
+ sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
+ err = err | cbor_encode_text_string(&rootMap, joinedTypes,
+ strlen(joinedTypes));
+ OICFree(joinedTypes);
+ }
+ else
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+ if (payload->interfaces)
+ {
+ char* joinedInterfaces = OCStringLLJoin(payload->interfaces);
+ if (joinedInterfaces)
+ {
+ err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_INTERFACE,
+ sizeof(OC_RSRVD_INTERFACE) - 1);
+ err = err | cbor_encode_text_string(&rootMap, joinedInterfaces,
+ strlen(joinedInterfaces));
+ OICFree(joinedInterfaces);
+ }
+ else
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ }
while(payload != NULL && (err == 0 || err == CborErrorOutOfMemory))
{
- err = err | OCConvertSingleRepPayload(&rootArray, payload);
+ err = err | OCConvertSingleRepPayload(&rootMap, payload);
payload = payload->next;
}
// Close main array
- err = err | cbor_encoder_close_container(&encoder, &rootArray);
+ err = err | cbor_encoder_close_container(&encoder, &rootMap);
return checkError(err, &encoder, outPayload, size);
}
int64_t err = 0;
cbor_encoder_init(&encoder, outPayload, *size, 0);
- CborEncoder rootArray;
-
- err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
-
CborEncoder map;
- err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+ err = err | cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
// Sequence Number
err = err | cbor_encode_text_string(&map,
}
// Close Map
- err = err | cbor_encoder_close_container(&rootArray, &map);
- err = err | cbor_encoder_close_container(&encoder, &rootArray);
+ err = err | cbor_encoder_close_container(&encoder, &map);
return checkError(err, &encoder, outPayload, size);
}
return OC_STACK_ERROR;
}
- if(!cbor_value_is_array(&rootValue))
- {
- OC_LOG_V(ERROR, TAG, "CBOR payload root object is not an array :%x", rootValue.type);
- return OC_STACK_MALFORMED_RESPONSE;
- }
-
- CborValue arrayValue;
- // enter the array
- err = err || cbor_value_enter_container(&rootValue, &arrayValue);
-
- if(err)
- {
- OC_LOG_V(ERROR, TAG, "CBOR payload parse failed :%d", err);
- return OC_STACK_MALFORMED_RESPONSE;
- }
-
OCStackResult result = OC_STACK_ERROR;
switch(payloadType)
{
case PAYLOAD_TYPE_DISCOVERY:
- result = OCParseDiscoveryPayload(outPayload, &arrayValue);
+ result = OCParseDiscoveryPayload(outPayload, &rootValue);
break;
case PAYLOAD_TYPE_DEVICE:
- result = OCParseDevicePayload(outPayload, &arrayValue);
+ result = OCParseDevicePayload(outPayload, &rootValue);
break;
case PAYLOAD_TYPE_PLATFORM:
- result = OCParsePlatformPayload(outPayload, &arrayValue);
+ result = OCParsePlatformPayload(outPayload, &rootValue);
break;
case PAYLOAD_TYPE_REPRESENTATION:
- result = OCParseRepPayload(outPayload, &arrayValue);
+ result = OCParseRepPayload(outPayload, &rootValue);
break;
case PAYLOAD_TYPE_PRESENCE:
- result = OCParsePresencePayload(outPayload, &arrayValue);
+ result = OCParsePresencePayload(outPayload, &rootValue);
break;
case PAYLOAD_TYPE_SECURITY:
- result = OCParseSecurityPayload(outPayload, &arrayValue);
+ result = OCParseSecurityPayload(outPayload, &rootValue);
break;
case PAYLOAD_TYPE_RD:
- result = OCRDCborToPayload(&arrayValue, outPayload);
+ result = OCRDCborToPayload(&rootValue, outPayload);
break;
default:
OC_LOG_V(ERROR, TAG, "ParsePayload Type default: %d", payloadType);
break;
}
- if(result == OC_STACK_OK)
- {
- err = err || cbor_value_leave_container(&rootValue, &arrayValue);
- if(err != CborNoError)
- {
- return OC_STACK_MALFORMED_RESPONSE;
- }
- }
- else
+ if(result != OC_STACK_OK)
{
OC_LOG_V(INFO, TAG, "Finished parse payload, result is %d", result);
}
void OCFreeOCStringLL(OCStringLL* ll);
-static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* rootValue)
{
if (!outPayload)
{
bool err = false;
char * securityData = NULL;
+ CborValue map;
+ size_t len;
- if(cbor_value_is_map(arrayVal))
- {
- CborValue curVal;
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
-
- if(cbor_value_is_valid(&curVal))
- {
- size_t len;
- err = err || cbor_value_dup_text_string(&curVal, &securityData, &len, NULL);
- }
- }
- else
- {
- OC_LOG(ERROR, TAG, "Cbor main value not a map");
- return OC_STACK_MALFORMED_RESPONSE;
- }
-
- err = err || cbor_value_advance(arrayVal);
+ err = err || cbor_value_enter_container(rootValue, &map);
+ err = err || cbor_value_dup_text_string(&map, &securityData, &len, NULL);
+ err = err || cbor_value_leave_container(rootValue, &map);
if(err)
{
return str;
}
-static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue* rootValue)
{
if (!outPayload)
{
bool err = false;
OCResourcePayload* resource = NULL;
+ uint16_t resourceCount = 0;
+ CborValue resourceMap = {};
OCDiscoveryPayload* out = OCDiscoveryPayloadCreate();
if(!out)
return OC_STACK_NO_MEMORY;
}
- if (cbor_value_is_array(arrayVal))
+ // Root value is already inside the main root array
+ CborValue rootMap = {};
+
+ // Enter the main root map
+ err = err || cbor_value_enter_container(rootValue, &rootMap);
+ // Look for DI
+ CborValue curVal = {};
+ err = cbor_value_map_find_value(&rootMap, OC_RSRVD_DEVICE_ID, &curVal);
+ if (CborNoError != err)
{
- OCLinksPayload *linksPayload = NULL;
- OCTagsPayload *tagsPayload = NULL;
- while (cbor_value_is_container(arrayVal))
- {
- linksPayload = NULL;
- tagsPayload = NULL;
- CborValue colResources;
- CborError cborFindResult = cbor_value_enter_container(arrayVal, &colResources);
- if (CborNoError != cborFindResult)
- {
- goto cbor_error;
- }
+ OC_LOG(ERROR, TAG, "Cbor find value failed.");
+ goto malformed_cbor;
+ }
+ size_t len;
+ err = cbor_value_dup_byte_string(&curVal, &(out->sid), &len, NULL);
- if (OC_STACK_OK != OCTagsCborToPayload(&colResources, &tagsPayload))
- {
- OC_LOG(ERROR, TAG, "Tags cbor parsing failed.");
- OCFreeTagsResource(tagsPayload);
- goto cbor_error;
- }
+ // Look for Links which will have an array as the value
+ err = cbor_value_map_find_value(&rootMap, OC_RSRVD_LINKS, &curVal);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor find value failed.");
+ goto malformed_cbor;
+ }
- if (OC_STACK_OK != OCLinksCborToPayload(&colResources, &linksPayload))
- {
- OC_LOG(ERROR, TAG, "Links cbor parsing failed.");
- OCFreeTagsResource(tagsPayload);
- OCFreeLinksResource(linksPayload);
- goto cbor_error;
- }
+ // Enter the links array and start iterating through the array processing
+ // each resource which shows up as a map.
+ err = err || cbor_value_enter_container(&curVal, &resourceMap);
- if (OC_STACK_OK != OCDiscoveryCollectionPayloadAddResource(out, tagsPayload, linksPayload))
- {
- OC_LOG(ERROR, TAG, "Memory allocation failed");
- OCFreeLinksResource(linksPayload);
- OCFreeTagsResource(tagsPayload);
- OCDiscoveryPayloadDestroy(out);
- return OC_STACK_NO_MEMORY;
- }
- if (CborNoError != cbor_value_advance(arrayVal))
- {
- OC_LOG(ERROR, TAG, "Cbor value advanced failed.");
- goto cbor_error;
- }
- }
- }
- if (cbor_value_is_map(arrayVal))
+ while (cbor_value_is_map(&resourceMap))
{
- size_t resourceCount = 0;
- while (cbor_value_is_map(arrayVal))
+ resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
+ if(!resource)
{
- resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
- if(!resource)
- {
- OC_LOG(ERROR, TAG, "Memory allocation failed");
- OCDiscoveryPayloadDestroy(out);
- return OC_STACK_NO_MEMORY;
- }
- CborValue curVal;
- // DI
- err = cbor_value_map_find_value(arrayVal, OC_RSRVD_DEVICE_ID, &curVal);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor find value failed.");
- goto malformed_cbor;
- }
- size_t len;
- err = cbor_value_dup_byte_string(&curVal, &(resource->sid), &len, NULL);
+ OC_LOG(ERROR, TAG, "Memory allocation failed");
+ OCDiscoveryPayloadDestroy(out);
+ return OC_STACK_NO_MEMORY;
+ }
+
+ // Uri
+ CborValue uriVal = {};
+ err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_HREF, &uriVal);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding href type failed.");
+ goto malformed_cbor;
+ }
+ err = cbor_value_dup_text_string(&uriVal, &(resource->uri), &len, NULL);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding href value failed.");
+ goto malformed_cbor;
+ }
+ // ResourceTypes
+ CborValue rtVal = {};
+ err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_RESOURCE_TYPE, &rtVal);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding rt type failed.");
+ goto malformed_cbor;
+ }
+ if (cbor_value_is_text_string(&rtVal))
+ {
+ char* input = NULL;
+ char* savePtr;
+ err = cbor_value_dup_text_string(&rtVal, &input, &len, NULL);
if (CborNoError != err)
{
- OC_LOG(ERROR, TAG, "Cbor di finding failed.");
+ OC_LOG(ERROR, TAG, "Cbor finding rt value failed.");
goto malformed_cbor;
}
- // Links TAG
+ if (input)
{
- CborValue linkArray;
- err = cbor_value_map_find_value(arrayVal, OC_RSRVD_LINKS, &linkArray);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor links finding failed.");
- goto malformed_cbor;
- }
- CborValue linkMap;
- err = cbor_value_enter_container(&linkArray, &linkMap);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor entering map failed.");
- goto malformed_cbor;
- }
- // Uri
- err = cbor_value_map_find_value(&linkMap, OC_RSRVD_HREF, &curVal);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding href type failed.");
- goto malformed_cbor;
- }
- err = cbor_value_dup_text_string(&curVal, &(resource->uri), &len, NULL);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding href value failed.");
- goto malformed_cbor;
- }
- // ResourceTypes
- CborValue rtVal;
- err = cbor_value_map_find_value(&linkMap, OC_RSRVD_RESOURCE_TYPE, &rtVal);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding rt type failed.");
- goto malformed_cbor;
- }
- if (cbor_value_is_text_string(&rtVal))
+ char* curPtr = strtok_r(input, " ", &savePtr);
+
+ while (curPtr)
{
- char* input = NULL;
- char* savePtr;
- err = cbor_value_dup_text_string(&rtVal, &input, &len, NULL);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding rt value failed.");
- goto malformed_cbor;
- }
- if (input)
+ char* trimmed = InPlaceStringTrim(curPtr);
+ if (trimmed[0] !='\0')
{
- char* curPtr = strtok_r(input, " ", &savePtr);
-
- while (curPtr)
+ if (!OCResourcePayloadAddResourceType(resource, trimmed))
{
- char* trimmed = InPlaceStringTrim(curPtr);
- if (trimmed[0] !='\0')
- {
- if (!OCResourcePayloadAddResourceType(resource, trimmed))
- {
- OICFree(resource->uri);
- OICFree(resource->sid);
- OCFreeOCStringLL(resource->types);
- OICFree(resource);
- OCDiscoveryPayloadDestroy(out);
- return OC_STACK_NO_MEMORY;
- }
- }
- curPtr = strtok_r(NULL, " ", &savePtr);
+ OICFree(resource->uri);
+ OCFreeOCStringLL(resource->types);
+ OICFree(resource);
+ OCDiscoveryPayloadDestroy(out);
+ return OC_STACK_NO_MEMORY;
}
- OICFree(input);
}
+ curPtr = strtok_r(NULL, " ", &savePtr);
}
+ OICFree(input);
+ }
+ }
- // Interface Types
- CborValue ifVal;
- err = cbor_value_map_find_value(&linkMap, OC_RSRVD_INTERFACE, &ifVal);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding if type failed.");
- goto malformed_cbor;
- }
- if (!err && cbor_value_is_text_string(&ifVal))
- {
- char* input = NULL;
- char* savePtr;
- err = cbor_value_dup_text_string(&ifVal, &input, &len, NULL);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding if value failed.");
- goto malformed_cbor;
- }
- if (input)
- {
- char* curPtr = strtok_r(input, " ", &savePtr);
+ // Interface Types
+ CborValue ifVal = {};
+ err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_INTERFACE, &ifVal);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding if type failed.");
+ goto malformed_cbor;
+ }
+ if (!err && cbor_value_is_text_string(&ifVal))
+ {
+ char* input = NULL;
+ char* savePtr;
+ err = cbor_value_dup_text_string(&ifVal, &input, &len, NULL);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding if value failed.");
+ goto malformed_cbor;
+ }
+ if (input)
+ {
+ char* curPtr = strtok_r(input, " ", &savePtr);
- while (curPtr)
- {
- char* trimmed = InPlaceStringTrim(curPtr);
- if (trimmed[0] !='\0')
- {
- if (!OCResourcePayloadAddInterface(resource, trimmed))
- {
- OICFree(resource->uri);
- OICFree(resource->sid);
- OCFreeOCStringLL(resource->types);
- OICFree(resource);
- OCDiscoveryPayloadDestroy(out);
- return OC_STACK_NO_MEMORY;
- }
- }
- curPtr = strtok_r(NULL, " ", &savePtr);
- }
- OICFree(input);
- }
- }
- // Policy
+ while (curPtr)
{
- CborValue policyMap;
- err = cbor_value_map_find_value(&linkMap, OC_RSRVD_POLICY, &policyMap);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding policy type failed.");
- goto malformed_cbor;
- }
- // Bitmap
- CborValue val;
- err = cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &val);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding bitmap type failed.");
- goto malformed_cbor;
- }
- uint64_t temp = 0;
- err = cbor_value_get_uint64(&val, &temp);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding bitmap value failed.");
- goto malformed_cbor;
- }
- resource->bitmap = (uint8_t)temp;
- // Secure Flag
- err = cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &val);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding secure type failed.");
- goto malformed_cbor;
- }
- if(cbor_value_is_valid(&val))
+ char* trimmed = InPlaceStringTrim(curPtr);
+ if (trimmed[0] !='\0')
{
- err = cbor_value_get_boolean(&val, &(resource->secure));
- if (CborNoError != err)
+ if (!OCResourcePayloadAddInterface(resource, trimmed))
{
- OC_LOG(ERROR, TAG, "Cbor finding secure value failed.");
- goto malformed_cbor;
- }
- // Port
- CborValue port;
- err = cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT,
- &port);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding port type failed.");
- goto malformed_cbor;
- }
- if(cbor_value_is_valid(&port))
- {
- err = cbor_value_get_uint64(&port, &temp);
- if (CborNoError != err)
- {
- OC_LOG(ERROR, TAG, "Cbor finding port value failed.");
- goto malformed_cbor;
- }
- resource->port = (uint16_t)temp;
+ OICFree(resource->uri);
+ OCFreeOCStringLL(resource->types);
+ OICFree(resource);
+ OCDiscoveryPayloadDestroy(out);
+ return OC_STACK_NO_MEMORY;
}
}
+ curPtr = strtok_r(NULL, " ", &savePtr);
}
+ OICFree(input);
+ }
+ }
+
+ // Policy
+ CborValue policyMap = {};
+ err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_POLICY, &policyMap);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding policy type failed.");
+ goto malformed_cbor;
+ }
+ // Bitmap
+ CborValue val = {};
+ err = cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &val);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding bitmap type failed.");
+ goto malformed_cbor;
+ }
+ uint64_t temp = 0;
+ err = cbor_value_get_uint64(&val, &temp);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding bitmap value failed.");
+ goto malformed_cbor;
+ }
+ resource->bitmap = (uint8_t)temp;
+ // Secure Flag
+ err = cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &val);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding secure type failed.");
+ goto malformed_cbor;
+ }
+ if(cbor_value_is_valid(&val))
+ {
+ err = cbor_value_get_boolean(&val, &(resource->secure));
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding secure value failed.");
+ goto malformed_cbor;
}
- err = cbor_value_advance(arrayVal);
+ // Port
+ CborValue port;
+ err = cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT,
+ &port);
if (CborNoError != err)
{
- OC_LOG(ERROR, TAG, "Cbor advance value failed.");
+ OC_LOG(ERROR, TAG, "Cbor finding port type failed.");
goto malformed_cbor;
}
- ++resourceCount;
- OCDiscoveryPayloadAddNewResource(out, resource);
+ if(cbor_value_is_valid(&port))
+ {
+ err = cbor_value_get_uint64(&port, &temp);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor finding port value failed.");
+ goto malformed_cbor;
+ }
+ resource->port = (uint16_t)temp;
+ }
+ }
+
+ err = cbor_value_advance(&resourceMap);
+ if (CborNoError != err)
+ {
+ OC_LOG(ERROR, TAG, "Cbor advance value failed.");
+ goto malformed_cbor;
}
+ ++resourceCount;
+ OCDiscoveryPayloadAddNewResource(out, resource);
}
+ err = err || cbor_value_leave_container(rootValue, &resourceMap);
+
*outPayload = (OCPayload*)out;
return OC_STACK_OK;
malformed_cbor:
OICFree(resource->uri);
- OICFree(resource->sid);
OCFreeOCStringLL(resource->types);
OCFreeOCStringLL(resource->interfaces);
OICFree(resource);
return OC_STACK_MALFORMED_RESPONSE;
}
-static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* rootValue)
{
if (!outPayload)
{
bool err = false;
- if(cbor_value_is_map(arrayVal))
+ if(cbor_value_is_map(rootValue))
{
- char* uri = NULL;
uint8_t* sid = NULL;
char* dname = NULL;
char* specVer = NULL;
char* dmVer = NULL;
- CborValue curVal;
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
- size_t len;
- err = err || cbor_value_dup_text_string(&curVal, &uri, &len, NULL);
- // Representation
+ CborValue repVal;
+ // Device ID
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DEVICE_ID, &repVal);
+ size_t len;
+ if(cbor_value_is_valid(&repVal))
{
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
-
- CborValue repVal;
- // Device ID
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DEVICE_ID, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_byte_string(&repVal, &sid, &len, NULL);
- }
- // Device Name
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DEVICE_NAME, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &dname, &len, NULL);
- }
- // Device Spec Version
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SPEC_VERSION, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &specVer, &len, NULL);
- }
-
- // Data Model Version
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DATA_MODEL_VERSION, &repVal);
- if (cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &dmVer, &len, NULL);
- }
+ err = err || cbor_value_dup_byte_string(&repVal, &sid, &len, NULL);
+ }
+ // Device Name
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DEVICE_NAME, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &dname, &len, NULL);
+ }
+ // Device Spec Version
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SPEC_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &specVer, &len, NULL);
+ }
+ // Data Model Version
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DATA_MODEL_VERSION, &repVal);
+ if (cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &dmVer, &len, NULL);
}
- err = err || cbor_value_advance(arrayVal);
+ err = err || cbor_value_advance(rootValue);
if(err)
{
- OICFree(uri);
OICFree(sid);
OICFree(dname);
OICFree(specVer);
return OC_STACK_MALFORMED_RESPONSE;
}
- *outPayload = (OCPayload*)OCDevicePayloadCreate(uri, sid, dname, specVer, dmVer);
+ *outPayload = (OCPayload*)OCDevicePayloadCreate(sid, dname, specVer, dmVer);
- OICFree(uri);
OICFree(sid);
OICFree(dname);
OICFree(specVer);
}
-static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* rootValue)
{
if (!outPayload)
{
bool err = false;
- if(cbor_value_is_map(arrayVal))
+ if(cbor_value_is_map(rootValue))
{
- char* uri = NULL;
OCPlatformInfo info = {0};
- CborValue curVal;
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
- size_t len;
- err = err || cbor_value_dup_text_string(&curVal, &uri, &len, NULL);
- // Representation
+ CborValue repVal;
+ size_t len;
+ // Platform ID
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_PLATFORM_ID, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.platformID), &len, NULL);
+ }
+
+ // MFG Name
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_NAME, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerName), &len, NULL);
+ }
+
+ // MFG URL
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_URL, &repVal);
+ if(cbor_value_is_valid(&repVal))
{
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
-
- CborValue repVal;
- // Platform ID
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_PLATFORM_ID, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.platformID), &len, NULL);
- }
-
- // MFG Name
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_NAME, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerName), &len, NULL);
- }
-
- // MFG URL
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_URL, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerUrl), &len, NULL);
- }
+ err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerUrl), &len, NULL);
+ }
- // Model Num
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MODEL_NUM, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.modelNumber), &len, NULL);
- }
+ // Model Num
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MODEL_NUM, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.modelNumber), &len, NULL);
+ }
- // Date of Mfg
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_DATE, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.dateOfManufacture), &len,
- NULL);
- }
+ // Date of Mfg
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_DATE, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.dateOfManufacture), &len,
+ NULL);
+ }
- // Platform Version
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_PLATFORM_VERSION, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.platformVersion), &len,
- NULL);
- }
+ // Platform Version
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_PLATFORM_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.platformVersion), &len, NULL);
+ }
- // OS Version
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_OS_VERSION, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.operatingSystemVersion),
- &len, NULL);
- }
+ // OS Version
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_OS_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.operatingSystemVersion),
+ &len, NULL);
+ }
- // Hardware Version
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_HARDWARE_VERSION, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.hardwareVersion), &len,
- NULL);
- }
+ // Hardware Version
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_HARDWARE_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.hardwareVersion), &len,
+ NULL);
+ }
- // Firmware Version
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_FIRMWARE_VERSION, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.firmwareVersion), &len,
- NULL);
- }
+ // Firmware Version
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_FIRMWARE_VERSION, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.firmwareVersion), &len,
+ NULL);
+ }
- // Support URL
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SUPPORT_URL, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.supportUrl), &len, NULL);
- }
+ // Support URL
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SUPPORT_URL, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.supportUrl), &len, NULL);
+ }
- // System Time
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SYSTEM_TIME, &repVal);
- if(cbor_value_is_valid(&repVal))
- {
- err = err || cbor_value_dup_text_string(&repVal, &(info.systemTime), &len, NULL);
- }
+ // System Time
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SYSTEM_TIME, &repVal);
+ if(cbor_value_is_valid(&repVal))
+ {
+ err = err || cbor_value_dup_text_string(&repVal, &(info.systemTime), &len, NULL);
}
- err = err || cbor_value_advance(arrayVal);
+ err = err || cbor_value_advance(rootValue);
if(err)
{
return OC_STACK_MALFORMED_RESPONSE;
}
- *outPayload = (OCPayload*)OCPlatformPayloadCreateAsOwner(uri, &info);
+ *outPayload = (OCPayload*)OCPlatformPayloadCreateAsOwner(&info);
if(!*outPayload)
{
while (!err && i < dimensions[0] && cbor_value_is_valid(&insideArray))
{
+ bool noAdvance = false;
if (cbor_value_get_type(&insideArray) != CborNullType)
{
switch (type)
err = err || OCParseSingleRepPayload(&tempPl, &insideArray);
((OCRepPayload**)targetArray)[i] = tempPl;
tempPl = NULL;
+ noAdvance = true;
}
else
{
}
}
++i;
- err = err || cbor_value_advance(&insideArray);
+ if (!noAdvance && cbor_value_is_valid(&insideArray))
+ {
+ err = err || cbor_value_advance(&insideArray);
+ }
}
return err;
return err;
}
-static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue* repParent)
+static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue *objMap)
{
if (!outPayload)
{
return false;
}
- *outPayload = OCRepPayloadCreate();
- OCRepPayload* curPayload = *outPayload;
bool err = false;
- if(!*outPayload)
- {
- return CborErrorOutOfMemory;
- }
-
- size_t len;
- CborValue curVal;
- err = err || cbor_value_map_find_value(repParent, OC_RSRVD_HREF, &curVal);
- if(cbor_value_is_valid(&curVal))
- {
- err = err || cbor_value_dup_text_string(&curVal, &curPayload->uri, &len,
- NULL);
- }
- err = err || cbor_value_map_find_value(repParent, OC_RSRVD_PROPERTY, &curVal);
- if(cbor_value_is_valid(&curVal))
+ if (cbor_value_is_map(objMap))
{
- CborValue insidePropValue = {0};
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_RESOURCE_TYPE,
- &insidePropValue);
-
- if(cbor_value_is_text_string(&insidePropValue))
+ if (!*outPayload)
{
- char* allRt = NULL;
- err = err || cbor_value_dup_text_string(&insidePropValue, &allRt, &len, NULL);
-
- char* savePtr;
-
- if (allRt)
+ *outPayload = OCRepPayloadCreate();
+ if(!*outPayload)
{
- char* curPtr = strtok_r(allRt, " ", &savePtr);
-
- while (curPtr)
- {
- char* trimmed = InPlaceStringTrim(curPtr);
- if (trimmed[0] != '\0')
- {
- OCRepPayloadAddResourceType(curPayload, curPtr);
- }
- curPtr = strtok_r(NULL, " ", &savePtr);
- }
+ return CborErrorOutOfMemory;
}
- OICFree(allRt);
}
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_INTERFACE, &insidePropValue);
-
- if(cbor_value_is_text_string(&insidePropValue))
- {
- char* allIf = NULL;
- err = err || cbor_value_dup_text_string(&insidePropValue, &allIf, &len, NULL);
-
- char* savePtr;
-
- if (allIf)
- {
- char* curPtr = strtok_r(allIf, " ", &savePtr);
-
- while (curPtr)
- {
- char* trimmed = InPlaceStringTrim(curPtr);
- if (trimmed[0] != '\0')
- {
- OCRepPayloadAddInterface(curPayload, curPtr);
- }
- curPtr = strtok_r(NULL, " ", &savePtr);
- }
- }
- OICFree(allIf);
- }
- }
+ OCRepPayload* curPayload = *outPayload;
- err = err || cbor_value_map_find_value(repParent, OC_RSRVD_REPRESENTATION, &curVal);
- if(cbor_value_is_map(&curVal))
- {
+ size_t len;
CborValue repMap;
- err = err || cbor_value_enter_container(&curVal, &repMap);
+ err = err || cbor_value_enter_container(objMap, &repMap);
while(!err && cbor_value_is_valid(&repMap))
{
char* name;
err = err || cbor_value_dup_text_string(&repMap, &name, &len, NULL);
-
err = err || cbor_value_advance(&repMap);
- int64_t intval = 0;
- bool boolval = false;
- char* strval = NULL;
- double doubleval = 0;
- OCRepPayload* pl;
-
- switch(cbor_value_get_type(&repMap))
+ CborType type = cbor_value_get_type(&repMap);
+ switch(type)
{
case CborNullType:
err = !OCRepPayloadSetNull(curPayload, name);
break;
case CborIntegerType:
- err = err || cbor_value_get_int64(&repMap, &intval);
- if (!err)
{
- err = !OCRepPayloadSetPropInt(curPayload, name, intval);
+ int64_t intval = 0;
+ err = err || cbor_value_get_int64(&repMap, &intval);
+ if (!err)
+ {
+ err = !OCRepPayloadSetPropInt(curPayload, name, intval);
+ }
}
break;
case CborDoubleType:
- err = err || cbor_value_get_double(&repMap, &doubleval);
- if (!err)
{
- err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval);
+ double doubleval = 0;
+ err = err || cbor_value_get_double(&repMap, &doubleval);
+ if (!err)
+ {
+ err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval);
+ }
}
break;
case CborBooleanType:
- err = err || cbor_value_get_boolean(&repMap, &boolval);
- if (!err)
{
- err = !OCRepPayloadSetPropBool(curPayload, name, boolval);
+ bool boolval = false;
+ err = err || cbor_value_get_boolean(&repMap, &boolval);
+ if (!err)
+ {
+ err = !OCRepPayloadSetPropBool(curPayload, name, boolval);
+ }
}
break;
case CborTextStringType:
- err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
- if (!err)
{
- err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
+ char* strval = NULL;
+ err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
+ if (!err)
+ {
+ err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
+ }
+ }
+ break;
+ case CborByteStringType:
+ {
+ uint8_t* bytestrval = NULL;
+ err = err || cbor_value_dup_byte_string(&repMap, &bytestrval, &len, NULL);
+ if (!err)
+ {
+ OCByteString tmp = {.bytes = bytestrval, .len = len};
+ err = !OCRepPayloadSetPropByteStringAsOwner(curPayload, name, &tmp);
+ }
}
break;
case CborMapType:
- err = err || OCParseSingleRepPayload(&pl, &repMap);
- if (!err)
{
- err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
+ OCRepPayload *pl = NULL;
+ err = err || OCParseSingleRepPayload(&pl, &repMap);
+ if (!err)
+ {
+ err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
+ }
}
break;
case CborArrayType:
err = true;
}
- err = err || cbor_value_advance(&repMap);
+ if (type != CborMapType && cbor_value_is_valid(&repMap))
+ {
+ err = err || cbor_value_advance(&repMap);
+ }
OICFree(name);
}
- err = err || cbor_value_leave_container(&curVal, &repMap);
- }
- if(err)
- {
- OCRepPayloadDestroy(*outPayload);
- *outPayload = NULL;
+ err = err || cbor_value_leave_container(objMap, &repMap);
+
+ if(err)
+ {
+ OCRepPayloadDestroy(*outPayload);
+ *outPayload = NULL;
+ }
}
return err;
}
-static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* arrayVal)
+
+static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* rootMap)
{
if (!outPayload)
{
return OC_STACK_INVALID_PARAM;
}
+ OCRepPayload *rootPayload = NULL;
+ OCRepPayload *curPayload = NULL;
+ OCRepPayload *temp = OCRepPayloadCreate();
+ if (!temp)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ CborValue curVal;
bool err = false;
+ size_t len;
+ err = err || cbor_value_map_find_value(rootMap, OC_RSRVD_RESOURCE_TYPE, &curVal);
+ if(cbor_value_is_text_string(&curVal))
+ {
+ char* allRt = NULL;
+ err = err || cbor_value_dup_text_string(&curVal, &allRt, &len, NULL);
+ if (allRt)
+ {
+ char* savePtr;
+ char* curPtr = strtok_r(allRt, " ", &savePtr);
+ while (curPtr)
+ {
+ char* trimmed = InPlaceStringTrim(curPtr);
+ if (trimmed[0] != '\0')
+ {
+ OCRepPayloadAddResourceType(temp, curPtr);
+ }
+ curPtr = strtok_r(NULL, " ", &savePtr);
+ }
+ }
+ OICFree(allRt);
+ }
- OCRepPayload* rootPayload = NULL;
- OCRepPayload* curPayload = NULL;
- OCRepPayload* temp = NULL;
- while(!err && cbor_value_is_map(arrayVal))
+ err = err || cbor_value_map_find_value(rootMap, OC_RSRVD_INTERFACE, &curVal);
+ if(cbor_value_is_text_string(&curVal))
{
- err = err || OCParseSingleRepPayload(&temp, arrayVal);
+ char* allIf = NULL;
+ err = err || cbor_value_dup_text_string(&curVal, &allIf, &len, NULL);
+ if (allIf)
+ {
+ char* savePtr;
+ char* curPtr = strtok_r(allIf, " ", &savePtr);
+ while (curPtr)
+ {
+ char* trimmed = InPlaceStringTrim(curPtr);
+ if (trimmed[0] != '\0')
+ {
+ OCRepPayloadAddInterface(temp, curPtr);
+ }
+ curPtr = strtok_r(NULL, " ", &savePtr);
+ }
+ }
+ OICFree(allIf);
+ }
+
+ while (!err && cbor_value_is_map(rootMap))
+ {
+ err = err || OCParseSingleRepPayload(&temp, rootMap);
if(rootPayload == NULL)
{
curPayload = curPayload->next;
}
+ if (cbor_value_is_valid(rootMap))
+ {
+ err = err || cbor_value_advance(rootMap);
+ }
- err = err || cbor_value_advance(arrayVal);
if(err)
{
OCRepPayloadDestroy(rootPayload);
return OC_STACK_OK;
}
-static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* rootValue)
{
if (!outPayload)
{
}
bool err = false;
- if(cbor_value_is_map(arrayVal))
+ if(cbor_value_is_map(rootValue))
{
uint64_t seqNum = 0;
uint64_t maxAge = 0;
CborValue curVal;
// Sequence Number
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_NONCE, &curVal);
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_NONCE, &curVal);
err = err || cbor_value_get_uint64(&curVal, &seqNum);
// Max Age
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_TTL, &curVal);
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_TTL, &curVal);
err = err || cbor_value_get_uint64(&curVal, &maxAge);
// Trigger
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_TRIGGER, &curVal);
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_TRIGGER, &curVal);
err = err || cbor_value_dup_text_string(&curVal, &tempStr, &len, NULL);
trigger = convertTriggerStringToEnum(tempStr);
OICFree(tempStr);
tempStr = NULL;
// Resource type name
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_RESOURCE_TYPE, &curVal);
+ err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_RESOURCE_TYPE, &curVal);
if(cbor_value_is_valid(&curVal))
{
err = err || cbor_value_dup_text_string(&curVal, &tempStr, &len, NULL);
}
- err = err || cbor_value_advance(arrayVal);
+ err = err || cbor_value_advance(rootValue);
if(!err)
{
if(payload)
{
+ ((OCDiscoveryPayload*)payload)->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
+ memcpy(((OCDiscoveryPayload*)payload)->sid,
+ OCGetServerInstanceID(), UUID_SIZE);
+
bool foundResourceAtRD = false;
for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
{
}
else
{
- payload = (OCPayload*) OCDevicePayloadCreate(OC_RSRVD_DEVICE_URI,
- (const uint8_t*) &deviceId->id, savedDeviceInfo.deviceName,
+ payload = (OCPayload*) OCDevicePayloadCreate((const uint8_t*) &deviceId->id, savedDeviceInfo.deviceName,
OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
if (!payload)
{
}
else if (virtualUriInRequest == OC_PLATFORM_URI)
{
- payload = (OCPayload*)OCPlatformPayloadCreate(
- OC_RSRVD_PLATFORM_URI,
- &savedPlatformInfo);
+ payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
if (!payload)
{
discoveryResult = OC_STACK_NO_MEMORY;
#ifdef RA_ADAPTER
, CA_ADAPTER_REMOTE_ACCESS
#endif
-
-#ifdef TCP_ADAPTER
, CA_ADAPTER_TCP
-#endif
};
size_t size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
#ifdef RA_ADAP
| CA_ADAPTER_REMOTE_ACCESS
#endif
-
-#ifdef TCP_ADAPTER
| CA_ADAPTER_TCP
-#endif
);
}
OCResource *headResource = NULL;
static OCResource *tailResource = NULL;
+static OCResourceHandle platformResource = {0};
+static OCResourceHandle deviceResource = {0};
#ifdef WITH_PRESENCE
static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
static PresenceResource presenceResource;
#endif
OCDeviceEntityHandler defaultDeviceHandler;
void* defaultDeviceHandlerCallbackParameter = NULL;
-
-#ifdef TCP_ADAPTER
static const char COAP_TCP[] = "coap+tcp:";
-#endif
//-----------------------------------------------------------------------------
// Macros
TAG, #arg " is NULL"); return (retVal); } }
#define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
TAG, #arg " is NULL"); return; } }
-#define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
+#define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL");\
goto exit;} }
//TODO: we should allow the server to define this
caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
}
-#ifdef TCP_ADAPTER
- if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
- {
- caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
- }
- if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
- {
- caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
- }
-#endif
-
defaultDeviceHandler = NULL;
defaultDeviceHandlerCallbackParameter = NULL;
- OCSeedRandom();
result = CAResultToOCResult(CAInitialize());
VERIFY_SUCCESS(result, OC_STACK_OK);
return OC_STACK_INVALID_URI;
}
-#ifdef TCP_ADAPTER
// process url scheme
size_t prefixLen = slash2 - fullUri;
bool istcp = false;
istcp = true;
}
}
-#endif
// TODO: this logic should come in with unit tests exercising the various strings
// processs url prefix, if any
{ // ipv4 address
colon = strchr(start, ':');
end = (colon && colon < slash) ? colon : slash;
-#ifdef TCP_ADAPTER
+
if (istcp)
{ // coap over tcp
adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
}
else
-#endif
{
adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
&(((OCResource *) presenceResource.handle)->resourceProperties),
OC_ACTIVE, 0);
#endif
-
+#ifndef WITH_ARDUINO
if (result == OC_STACK_OK)
{
result = SRMInitSecureResources();
}
+#endif
+
+ if(result == OC_STACK_OK)
+ {
+ result = OCCreateResource(&deviceResource,
+ OC_RSRVD_RESOURCE_TYPE_DEVICE,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_DEVICE_URI,
+ NULL,
+ NULL,
+ OC_DISCOVERABLE);
+ if(result == OC_STACK_OK)
+ {
+ result = BindResourceInterfaceToResource((OCResource *)deviceResource,
+ OC_RSRVD_INTERFACE_READ);
+ }
+ }
+
+ if(result == OC_STACK_OK)
+ {
+ result = OCCreateResource(&platformResource,
+ OC_RSRVD_RESOURCE_TYPE_PLATFORM,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_PLATFORM_URI,
+ NULL,
+ NULL,
+ OC_DISCOVERABLE);
+ if(result == OC_STACK_OK)
+ {
+ result = BindResourceInterfaceToResource((OCResource *)platformResource,
+ OC_RSRVD_INTERFACE_READ);
+ }
+ }
return result;
}
{
OC_LOG(INFO, TAG, "Build OCAction Instance.");
- if(action)
- {
- OICFree(action->resourceUri);
- OICFree(action);
- }
action = (OCAction*) OICMalloc(sizeof(OCAction));
VARIFY_POINTER_NULL(action, result, exit)
memset(action, 0, sizeof(OCAction));
int flags = 0;
cbor_encoder_init(&encoder, outPayload, *size, flags);
- CborEncoder rootArray;
CborError cborEncoderResult;
- cborEncoderResult = cbor_encoder_create_array(&encoder, &rootArray, CBOR_ROOT_ARRAY_LENGTH);
- if (CborNoError != cborEncoderResult)
- {
- OC_LOG(ERROR, TAG, "Failed creating cbor array.");
- goto cbor_error;
- }
-
if (rdPayload->rdDiscovery)
{
CborEncoder map;
- cborEncoderResult = cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+ cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
if (CborNoError != cborEncoderResult)
{
OC_LOG(ERROR, TAG, "Failed creating discovery map.");
OC_LOG(ERROR, TAG, "Failed setting OC_RSRVD_RD_DISCOVERY_SEL.");
goto cbor_error;
}
- cborEncoderResult = cbor_encoder_close_container(&rootArray, &map);
+ cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
if (CborNoError != cborEncoderResult)
{
OC_LOG(ERROR, TAG, "Failed closing discovery map.");
else if (rdPayload->rdPublish)
{
CborEncoder colArray;
- cborEncoderResult = cbor_encoder_create_array(&rootArray, &colArray, CborIndefiniteLength);
+ cborEncoderResult = cbor_encoder_create_array(&encoder, &colArray, CborIndefiniteLength);
if (CborNoError != cborEncoderResult)
{
OC_LOG(ERROR, TAG, "Failed creating collection array.");
}
rdPublish = rdPublish->next;
}
- cborEncoderResult = cbor_encoder_close_container(&rootArray, &colArray);
+ cborEncoderResult = cbor_encoder_close_container(&encoder, &colArray);
if (CborNoError != cborEncoderResult)
{
OC_LOG(ERROR, TAG, "Failed closing collection array.");
goto cbor_error;
}
}
- cborEncoderResult = cbor_encoder_close_container(&encoder, &rootArray);
- if (CborNoError != cborEncoderResult)
+ else
{
- OC_LOG(ERROR, TAG, "Failed closing root array container. ");
- goto cbor_error;
+ CborEncoder map;
+ cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating discovery map.");
+ goto cbor_error;
+ }
+ cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating discovery map.");
+ goto cbor_error;
+ }
}
-
*size = encoder.ptr - outPayload;
- return OC_STACK_OK;
+ return OC_STACK_OK;
cbor_error:
OICFree(outPayload);
return OC_STACK_ERROR;
'../../security/include',
'../../ocsocket/include',
'../../logger/include',
- '../../ocrandom/include',
+ '../../../c_common/ocrandom/include',
'../../stack/include',
'../../stack/include/internal',
'../../connectivity/api',
examples_env.AppendUnique(CPPPATH = [
'../include/',
'../csdk/stack/include',
- '../csdk/ocrandom/include',
+ '../c_common/ocrandom/include',
'../csdk/logger/include',
'../oc_logger/include'
])
virtual ~OCRepresentation(){}
+ void setDevAddr(const OCDevAddr addr);
+
+ const std::string getHost() const;
+
OCRepPayload* getPayload() const;
void addChild(const OCRepresentation&);
if(x!= m_values.end())
{
- val = boost::get<T>(x->second);
- return true;
+ try
+ {
+ val = boost::get<T>(x->second);
+ return true;
+ }
+ catch (boost::bad_get& e)
+ {
+ val = T();
+ return false;
+ }
}
else
{
auto x = m_values.find(str);
if(x != m_values.end())
{
- val = boost::get<T>(x->second);
+ try
+ {
+ val = boost::get<T>(x->second);
+ }
+ catch (boost::bad_get& e)
+ {
+ return val;
+ }
}
return val;
}
bool isNULL(const std::string& str) const;
+ private:
+ std::string m_host;
+
// STL Container stuff
public:
class iterator;
template<typename T>
T getValue() const
{
- return boost::get<T>(m_values[m_attrName]);
+ try
+ {
+ return boost::get<T>(m_values[m_attrName]);
+ }
+ catch (boost::bad_get& e)
+ {
+ T val = T();
+ return val;
+ }
}
std::string getValueToString() const;
#include <StringConstants.h>
#include "ocpayload.h"
#include "ocrandom.h"
+#include "oic_string.h"
namespace OC
{
while(res)
{
char uuidString[UUID_STRING_SIZE];
- if(OCConvertUuidToString(res->sid, uuidString) != RAND_UUID_OK)
+ if(OCConvertUuidToString(payload->sid, uuidString) != RAND_UUID_OK)
{
uuidString[0]= '\0';
}
{
while(colRes)
{
+ // currently support for ipv4 is provided.
+ OCDevAddr colAddr;
+ colAddr.adapter = OC_ADAPTER_IP;
+ colAddr.flags = OC_IP_USE_V4;
+ char *ptr = strtok(colRes->tags->baseURI, ":");
+ OICStrcpy(colAddr.addr, sizeof(colAddr.addr), ptr);
+
if (colRes->tags->bitmap & OC_SECURE)
{
- m_devAddr.flags =
+ colAddr.flags =
(OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags);
}
-
if (colRes->tags->port != 0)
{
- m_devAddr.port = colRes->tags->port;
+ colAddr.port = colRes->tags->port;
+ }
+ else
+ {
+ colAddr.port = atoi(ptr+1);
}
m_resources.push_back(std::shared_ptr<OC::OCResource>(
- new OC::OCResource(m_clientWrapper, m_devAddr,
+ new OC::OCResource(m_clientWrapper, colAddr,
std::string(colRes->setLinks->href),
std::string((char*)colRes->tags->di.id),
(colRes->tags->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
// first one is considered the root, everything else is considered a child of this one.
OCRepresentation root = *it;
+ root.setDevAddr(clientResponse->devAddr);
++it;
std::for_each(it, oc.representations().end(),
namespace OC
{
+ static const char COAP[] = "coap://";
+ static const char COAPS[] = "coaps://";
+ static const char COAP_TCP[] = "coap+tcp://";
void MessageContainer::setPayload(const OCPayload* rep)
{
void MessageContainer::setPayload(const OCDevicePayload* payload)
{
OCRepresentation rep;
- rep.setUri(payload->uri);
char uuidString[UUID_STRING_SIZE];
if(payload->sid && RAND_UUID_OK == OCConvertUuidToString(payload->sid, uuidString))
{
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();
{
m_children = children;
}
+
+ void OCRepresentation::setDevAddr(const OCDevAddr m_devAddr)
+ {
+ std::ostringstream ss;
+ if (m_devAddr.flags & OC_SECURE)
+ {
+ ss << COAPS;
+ }
+ else if (m_devAddr.adapter & OC_ADAPTER_TCP)
+ {
+ ss << COAP_TCP;
+ }
+ else
+ {
+ ss << COAP;
+ }
+ if (m_devAddr.flags & OC_IP_USE_V6)
+ {
+ ss << '[' << m_devAddr.addr << ']';
+ }
+ else
+ {
+ ss << m_devAddr.addr;
+ }
+ if (m_devAddr.port)
+ {
+ ss << ':' << m_devAddr.port;
+ }
+ m_host = ss.str();
+ }
+
+ const std::string OCRepresentation::getHost() const
+ {
+ return m_host;
+ }
+
void OCRepresentation::setUri(const char* uri)
{
m_uri = uri ? uri : "";
static const char COAP[] = "coap://";
static const char COAPS[] = "coaps://";
-
-#ifdef TCP_ADAPTER
static const char COAP_TCP[] = "coap+tcp://";
-#endif
using OC::nil_guard;
using OC::result_guard;
prefix_len = sizeof(COAPS) - 1;
m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags & OC_SECURE);
}
-#ifdef TCP_ADAPTER
else if (host.compare(0, sizeof(COAP_TCP) - 1, COAP_TCP) == 0)
{
prefix_len = sizeof(COAP_TCP) - 1;
m_devAddr.adapter = static_cast<OCTransportAdapter>(m_devAddr.adapter & OC_ADAPTER_TCP);
}
-#endif
else
{
throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
{
ss << COAPS;
}
-#ifdef TCP_ADAPTER
else if (m_devAddr.adapter & OC_ADAPTER_TCP)
{
ss << COAP_TCP;
}
-#endif
else
{
ss << COAP;
oclib_env.AppendUnique(CPPPATH = [
'../include/',
'../csdk/stack/include',
- '../csdk/ocrandom/include',
+ '../c_common/ocrandom/include',
'../csdk/logger/include',
'../oc_logger/include',
'../csdk/connectivity/lib/libcoap-4.1.1'
# Build Common unit tests
SConscript('c_common/oic_string/test/SConscript')
SConscript('c_common/oic_malloc/test/SConscript')
+ SConscript('c_common/ocrandom/test/SConscript')
# Build C unit tests
SConscript('csdk/stack/test/SConscript')
- SConscript('csdk/ocrandom/test/SConscript')
SConscript('csdk/connectivity/test/SConscript')
// CBOR->OCPayload and OCPayload->OCRepresentation conversions
namespace OCRepresentationEncodingTest
{
-
- static const char uri1[] = "/testuri";
static const uint8_t sid1[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
static const char devicename1[] = "device name";
static const char specver1[] = "spec version";
TEST(DeviceDiscoveryEncoding, Normal)
{
OCDevicePayload* device = OCDevicePayloadCreate(
- uri1,
sid1,
devicename1,
specver1,
dmver1);
- EXPECT_STREQ(uri1, device->uri);
EXPECT_STREQ(devicename1, device->deviceName);
EXPECT_STREQ(specver1, device->specVersion);
EXPECT_STREQ(dmver1, device->dataModelVersion);
cborData, cborSize));
OICFree(cborData);
- EXPECT_STREQ(device->uri, ((OCDevicePayload*)parsedDevice)->uri);
EXPECT_STREQ(device->deviceName, ((OCDevicePayload*)parsedDevice)->deviceName);
EXPECT_STREQ(device->specVersion, ((OCDevicePayload*)parsedDevice)->specVersion);
EXPECT_STREQ(device->dataModelVersion, ((OCDevicePayload*)parsedDevice)->dataModelVersion);
mc.setPayload(parsedDevice);
EXPECT_EQ(1u, mc.representations().size());
const OC::OCRepresentation& r = mc.representations()[0];
- EXPECT_STREQ(uri1, r.getUri().c_str());
EXPECT_STREQ(devicename1, r.getValue<std::string>(OC_RSRVD_DEVICE_NAME).c_str());
EXPECT_STREQ(specver1, r.getValue<std::string>(OC_RSRVD_SPEC_VERSION).c_str());
EXPECT_STREQ(dmver1, r.getValue<std::string>(OC_RSRVD_DATA_MODEL_VERSION).c_str());
-
OCPayloadDestroy(parsedDevice);
}
+ static const char uri1[] = "/testuri";
static char pfid1[] = "pfid";
static char mfgnm1[] = "mfgnm";
static char mfgurl1[] = "mfgurl";
{
OCPlatformInfo info {pfid1, mfgnm1, mfgurl1, modelnum1, dom1, pfver1, osver1, hwver1,
fwver1, url1, time1};
- OCPlatformPayload* platform = OCPlatformPayloadCreate(uri1, &info);
+ OCPlatformPayload* platform = OCPlatformPayloadCreate(&info);
EXPECT_EQ(PAYLOAD_TYPE_PLATFORM, ((OCPayload*)platform)->type);
- EXPECT_STREQ(uri1, platform->uri);
EXPECT_STREQ(pfid1, platform->info.platformID);
EXPECT_STREQ(mfgnm1, platform->info.manufacturerName);
EXPECT_STREQ(mfgurl1, platform->info.manufacturerUrl);
EXPECT_EQ(platform->base.type, ((OCPlatformPayload*)parsedPlatform)->base.type);
OCPlatformPayload* platform2 = (OCPlatformPayload*)parsedPlatform;
- EXPECT_STREQ(platform->uri, platform2->uri);
EXPECT_STREQ(platform->info.platformID, platform2->info.platformID);
EXPECT_STREQ(platform->info.manufacturerName, platform->info.manufacturerName);
EXPECT_STREQ(platform->info.manufacturerUrl, platform->info.manufacturerUrl);
mc.setPayload(parsedPlatform);
EXPECT_EQ(1u, mc.representations().size());
const OC::OCRepresentation& r = mc.representations()[0];
- EXPECT_STREQ(uri1, r.getUri().c_str());
EXPECT_STREQ(pfid1, r.getValue<std::string>(OC_RSRVD_PLATFORM_ID).c_str());
EXPECT_STREQ(mfgnm1, r.getValue<std::string>(OC_RSRVD_MFG_NAME).c_str());
EXPECT_STREQ(mfgurl1, r.getValue<std::string>(OC_RSRVD_MFG_URL).c_str());
OCPayloadDestroy(parsedPlatform);
}
+ TEST(PresencePayload, Normal)
+ {
+ uint32_t maxAge = 0;
+ uint32_t sequenceNumber = 0;
+ OCPresenceTrigger trigger = OC_PRESENCE_TRIGGER_CREATE;
+ OCPresencePayload *presence = OCPresencePayloadCreate(sequenceNumber, maxAge, trigger, uri1);
+
+ uint8_t* cborData;
+ size_t cborSize;
+ OCPayload* cparsed;
+ EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*)presence, &cborData, &cborSize));
+ EXPECT_EQ(OC_STACK_OK, OCParsePayload(&cparsed, PAYLOAD_TYPE_PRESENCE,
+ cborData, cborSize));
+ OCPayloadDestroy((OCPayload*)presence);
+ OICFree(cborData);
+ OCPresencePayload* parsed = ((OCPresencePayload*)cparsed);
+ EXPECT_EQ(sequenceNumber, parsed->sequenceNumber);
+ EXPECT_EQ(maxAge, parsed->maxAge);
+ EXPECT_EQ(trigger, parsed->trigger);
+ EXPECT_STREQ(uri1, parsed->resourceType);
+
+ OCPayloadDestroy(cparsed);
+ }
// Representation Payloads
TEST(RepresentationEncoding, BaseAttributeTypes)
{
{
OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
+ payload->sid = (uint8_t*)OICMalloc(16);
payload->resources = resource;
OCResourcePayloadAddResourceType(resource, "rt.singleitem");
OCResourcePayloadAddInterface(resource, "if.singleitem");
resource->uri = OICStrdup("/uri/thing");
- resource->sid = (uint8_t*)OICMalloc(16);
uint8_t* cborData;
size_t cborSize;
TEST(DiscoveryRTandIF, SingleItemFrontTrim)
{
OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ payload->sid = (uint8_t*)OICMalloc(16);
OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
payload->resources = resource;
OCResourcePayloadAddResourceType(resource, " rt.singleitem");
OCResourcePayloadAddInterface(resource, " if.singleitem");
resource->uri = OICStrdup("/uri/thing");
- resource->sid = (uint8_t*)OICMalloc(16);
uint8_t* cborData;
size_t cborSize;
TEST(DiscoveryRTandIF, SingleItemBackTrim)
{
OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ payload->sid = (uint8_t*)OICMalloc(16);
OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
payload->resources = resource;
OCResourcePayloadAddResourceType(resource, "rt.singleitem ");
OCResourcePayloadAddInterface(resource, "if.singleitem ");
resource->uri = OICStrdup("/uri/thing");
- resource->sid = (uint8_t*)OICMalloc(16);
uint8_t* cborData;
size_t cborSize;
TEST(DiscoveryRTandIF, SingleItemBothTrim)
{
OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ payload->sid = (uint8_t*)OICMalloc(16);
OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
payload->resources = resource;
OCResourcePayloadAddResourceType(resource, " rt.singleitem ");
OCResourcePayloadAddInterface(resource, " if.singleitem ");
resource->uri = OICStrdup("/uri/thing");
- resource->sid = (uint8_t*)OICMalloc(16);
uint8_t* cborData;
size_t cborSize;
TEST(DiscoveryRTandIF, MultiItemsNormal)
{
OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ payload->sid = (uint8_t*)OICMalloc(16);
OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
payload->resources = resource;
OCResourcePayloadAddInterface(resource, "if.firstitem");
OCResourcePayloadAddInterface(resource, "if.seconditem");
resource->uri = OICStrdup("/uri/thing");
- resource->sid = (uint8_t*)OICMalloc(16);
uint8_t* cborData;
size_t cborSize;
TEST(DiscoveryRTandIF, MultiItemExtraLeadSpaces)
{
OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ payload->sid = (uint8_t*)OICMalloc(16);
OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
payload->resources = resource;
OCResourcePayloadAddInterface(resource, " if.firstitem");
OCResourcePayloadAddInterface(resource, " if.seconditem");
resource->uri = OICStrdup("/uri/thing");
- resource->sid = (uint8_t*)OICMalloc(16);
uint8_t* cborData;
size_t cborSize;
TEST(DiscoveryRTandIF, MultiItemExtraTrailSpaces)
{
OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ payload->sid = (uint8_t*)OICMalloc(16);
OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
payload->resources = resource;
OCResourcePayloadAddInterface(resource, "if.firstitem ");
OCResourcePayloadAddInterface(resource, "if.seconditem ");
resource->uri = OICStrdup("/uri/thing");
- resource->sid = (uint8_t*)OICMalloc(16);
uint8_t* cborData;
size_t cborSize;
TEST(DiscoveryRTandIF, MultiItemBothSpaces)
{
OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+ payload->sid = (uint8_t*)OICMalloc(16);
OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
payload->resources = resource;
OCResourcePayloadAddInterface(resource, " if.firstitem ");
OCResourcePayloadAddInterface(resource, " if.seconditem ");
resource->uri = OICStrdup("/uri/thing");
- resource->sid = (uint8_t*)OICMalloc(16);
uint8_t* cborData;
size_t cborSize;
TEST(RepresentationEncodingRTandIF, SingleItemNormal)
{
OCRepPayload* payload = OCRepPayloadCreate();
- OCRepPayloadSetUri(payload, "/this/uri");
OCRepPayloadAddResourceType(payload, "rt.firstitem");
OCRepPayloadAddInterface(payload, "if.firstitem");
TEST(RepresentationEncodingRTandIF, SingleItemFrontTrim)
{
OCRepPayload* payload = OCRepPayloadCreate();
- OCRepPayloadSetUri(payload, "/this/uri");
OCRepPayloadAddResourceType(payload, " rt.firstitem");
OCRepPayloadAddInterface(payload, " if.firstitem");
TEST(RepresentationEncodingRTandIF, SingleItemBackTrim)
{
OCRepPayload* payload = OCRepPayloadCreate();
- OCRepPayloadSetUri(payload, "/this/uri");
OCRepPayloadAddResourceType(payload, "rt.firstitem ");
OCRepPayloadAddInterface(payload, "if.firstitem ");
TEST(RepresentationEncodingRTandIF, SingleItemBothTrim)
{
OCRepPayload* payload = OCRepPayloadCreate();
- OCRepPayloadSetUri(payload, "/this/uri");
OCRepPayloadAddResourceType(payload, " rt.firstitem ");
OCRepPayloadAddInterface(payload, " if.firstitem ");
TEST(RepresentationEncodingRTandIF, MultiItemsNormal)
{
OCRepPayload* payload = OCRepPayloadCreate();
- OCRepPayloadSetUri(payload, "/this/uri");
OCRepPayloadAddResourceType(payload, "rt.firstitem");
OCRepPayloadAddResourceType(payload, "rt.seconditem");
OCRepPayloadAddInterface(payload, "if.firstitem");
TEST(RepresentationEncodingRTandIF, MultiItemExtraLeadSpaces)
{
OCRepPayload* payload = OCRepPayloadCreate();
- OCRepPayloadSetUri(payload, "/this/uri");
OCRepPayloadAddResourceType(payload, " rt.firstitem");
OCRepPayloadAddResourceType(payload, " rt.seconditem");
OCRepPayloadAddInterface(payload, " if.firstitem");
TEST(RepresentationEncodingRTandIF, MultiItemExtraTrailSpaces)
{
OCRepPayload* payload = OCRepPayloadCreate();
- OCRepPayloadSetUri(payload, "/this/uri");
OCRepPayloadAddResourceType(payload, "rt.firstitem ");
OCRepPayloadAddResourceType(payload, "rt.seconditem ");
OCRepPayloadAddInterface(payload, "if.firstitem ");
TEST(RepresentationEncodingRTandIF, MultiItemExtraMiddleSpaces)
{
OCRepPayload* payload = OCRepPayloadCreate();
- OCRepPayloadSetUri(payload, "/this/uri");
OCRepPayloadAddResourceType(payload, " rt.firstitem ");
OCRepPayloadAddResourceType(payload, " rt.seconditem ");
OCRepPayloadAddInterface(payload, " if.firstitem ");
EXPECT_EQ(nullptr, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
int badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<int>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout);
int badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<int>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
(void)badout;
}
EXPECT_EQ(repsource.getUri(), repout2.getUri());
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(repsource, repout2);
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(inner2.getUri(), repout2[1].getUri());
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(inner4.getUri(), repout2[1][1].getUri());
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
EXPECT_EQ(inner8.getUri(), repout2[1][1][1].getUri());
double badout;
- EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
string badoutstr;
- EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+ EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
(void)badout;
(void)badoutstr;
}
'../csdk/connectivity/api',
'../csdk/connectivity/external/inc',
'../csdk/ocsocket/include',
- '../csdk/ocrandom/include',
+ '../c_common/ocrandom/include',
'../csdk/logger/include',
'#extlibs/gtest/gtest-1.7.0/include',
'#extlibs/hippomocks-master/HippoMocks',
{
public:
BMISensorResource();
+ BMISensorResource(const BMISensorResource &other)=delete;
+ BMISensorResource& operator=( const BMISensorResource& rhs )=delete;
~BMISensorResource();
virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
#include "BMISensorResource.h"
-BMISensorBundleActivator *bundle;
+BMISensorBundleActivator *g_bundleBMI;
BMISensorBundleActivator::BMISensorBundleActivator()
{
extern "C" void bmisensor_externalActivateBundle(ResourceContainerBundleAPI *resourceContainer,
std::string bundleId)
{
- bundle = new BMISensorBundleActivator();
- bundle->activateBundle(resourceContainer, bundleId);
+ g_bundleBMI = new BMISensorBundleActivator();
+ g_bundleBMI->activateBundle(resourceContainer, bundleId);
}
extern "C" void bmisensor_externalDeactivateBundle()
{
- bundle->deactivateBundle();
- delete bundle;
+ g_bundleBMI->deactivateBundle();
+ delete g_bundleBMI;
}
extern "C" void bmisensor_externalCreateResource(resourceInfo resourceInfo)
{
- bundle->createResource(resourceInfo);
+ g_bundleBMI->createResource(resourceInfo);
}
extern "C" void bmisensor_externalDestroyResource(BundleResource::Ptr pBundleResource)
{
- bundle->destroyResource(pBundleResource);
+ g_bundleBMI->destroyResource(pBundleResource);
}
#define MAX_PATH 2048
-/* Annother way to create a context: */
+/* Another way to create a context: */
auto info_logger = []() -> boost::iostreams::stream<OC::oc_log_stream> &
{
static OC::oc_log_stream ols(oc_make_ostream_logger);
static boost::iostreams::stream<OC::oc_log_stream> os(ols);
-
return os;
};
//******************************************************************
//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-// OCClient.cpp : Defines the entry point for the console application.
-//
+
#include <string>
#include <map>
#include <cstdlib>
std::cout << "Posting light representation..." << std::endl;
- mylight.m_on_off = "false";
+ mylight.m_on_off = false;
rep.setValue("on-off", mylight.m_on_off);
public:
DiscomfortIndexSensorResource();
~DiscomfortIndexSensorResource();
+ DiscomfortIndexSensorResource(const DiscomfortIndexSensorResource &other)=delete;
+ DiscomfortIndexSensorResource& operator=( const DiscomfortIndexSensorResource& rhs )=delete;
virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
#include <sstream>
#include "DiscomfortIndexSensorResource.h"
-DISensorBundleActivator *bundle;
+DISensorBundleActivator *g_bundleDI;
DISensorBundleActivator::DISensorBundleActivator()
{
extern "C" void disensor_externalActivateBundle(ResourceContainerBundleAPI *resourceContainer,
std::string bundleId)
{
- bundle = new DISensorBundleActivator();
- bundle->activateBundle(resourceContainer, bundleId);
+ g_bundleDI = new DISensorBundleActivator();
+ g_bundleDI->activateBundle(resourceContainer, bundleId);
}
extern "C" void disensor_externalDeactivateBundle()
{
- bundle->deactivateBundle();
- delete bundle;
+ g_bundleDI->deactivateBundle();
+ delete g_bundleDI;
}
extern "C" void disensor_externalCreateResource(resourceInfo resourceInfo)
{
- bundle->createResource(resourceInfo);
+ g_bundleDI->createResource(resourceInfo);
}
extern "C" void disensor_externalDestroyResource(BundleResource::Ptr pBundleResource)
{
- bundle->destroyResource(pBundleResource);
+ g_bundleDI->destroyResource(pBundleResource);
}
{
executeLogic();
}
-}
\ No newline at end of file
+}
using namespace OIC::Service;
-HueSampleBundleActivator *bundle;
+HueSampleBundleActivator *g_bundleHUE;
HueSampleBundleActivator::HueSampleBundleActivator()
{
extern "C" void huesample_externalActivateBundle(ResourceContainerBundleAPI *resourceContainer,
std::string bundleId)
{
- bundle = new HueSampleBundleActivator();
- bundle->activateBundle(resourceContainer, bundleId);
+ g_bundleHUE = new HueSampleBundleActivator();
+ g_bundleHUE->activateBundle(resourceContainer, bundleId);
}
extern "C" void huesample_externalDeactivateBundle()
{
- bundle->deactivateBundle();
- delete bundle;
+ g_bundleHUE->deactivateBundle();
+ delete g_bundleHUE;
}
extern "C" void huesample_externalCreateResource(resourceInfo resourceInfo)
{
- bundle->createResource(resourceInfo);
+ g_bundleHUE->createResource(resourceInfo);
}
extern "C" void huesample_externalDestroyResource(BundleResource::Ptr pBundleResource)
{
- bundle->destroyResource(pBundleResource);
+ g_bundleHUE->destroyResource(pBundleResource);
}
</option>
<option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
- <listOptionValue builtIn="false" value=""C:\boost_1_56_0""/>
<listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\resourceBroker\include""/>
<listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\resourceCache\include""/>
<listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\common\utils\include""/>
// This button is set for devices which doesn't have H/W back key.
btn = elm_button_add(nf);
elm_object_style_set(btn, "naviframe/end_btn/default");
- nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
+ nf_it = elm_naviframe_item_push(nf, "Container Client", btn, NULL, list, NULL);
elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
}
evas_object_size_hint_align_set(log_entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
elm_object_part_content_set(layout, "log", log_entry);
- nf_it = elm_naviframe_item_push(nf, "Resource Container", NULL, NULL, scroller, NULL);
+ nf_it = elm_naviframe_item_push(nf, "Container Client", NULL, NULL, scroller, NULL);
elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
// Show the UI list of group APIs
</option>
<option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
- <listOptionValue builtIn="false" value=""C:\boost_1_56_0""/>
<listOptionValue builtIn="false" value=""..\..\..\..\src\resourceBroker\include""/>
<listOptionValue builtIn="false" value=""..\..\..\..\src\resourceCache\include""/>
<listOptionValue builtIn="false" value=""..\..\..\..\src\common\utils\include""/>
void *showContainerAPIs(void *data);
-void containerCreateUI(void *data);
-
static void startContainer(void *data, Evas_Object *obj, void *event_info);
static void stopContainer(void *data, Evas_Object *obj, void *event_info);
#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.containerserver/res/ui_controls.edj"
-void containerCreateUI(void *data, Evas_Object *obj, void *event_info);
+void containerCreateUI(void *data);
#endif // RCMAIN_H__
s_containerFlag = true;
s_hueBundleFlag = true;
logMessage += "CONTAINER STARTED<br>";
- logMessage += "ADD AND START BUNDLES<br>";
+ logMessage += "HUE BUNDLE STARTED<br>";
}
else
{
evas_object_del(listnew);
listnew = NULL;
}
+
+ ui_app_exit();
return EINA_TRUE;
}
// Method to set up server screens
-void containerCreateUI(void *data, Evas_Object *obj, void *event_info)
+void containerCreateUI(void *data)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### container UI");
s_containerFlag = false;
s_hueBundleFlag = false;
Evas_Object *layout;
scroller = elm_scroller_add(nf);
elm_scroller_bounce_set(scroller, EINA_FALSE, EINA_TRUE);
elm_scroller_policy_set(scroller, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_AUTO);
- dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 1");
// Layout
layout = elm_layout_add(nf);
evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_object_content_set(scroller, layout);
- dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 2");
// Button
start_button = elm_button_add(layout);
elm_object_part_content_set(layout, "start_button", start_button);
elm_object_text_set(start_button, "Start Container");
evas_object_smart_callback_add(start_button, "clicked", startContainer, NULL);
- dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 3");
// Button
stop_button = elm_button_add(layout);
elm_object_part_content_set(layout, "stop_button", stop_button);
elm_object_text_set(stop_button, "Stop Container");
evas_object_smart_callback_add(stop_button, "clicked", stopContainer, NULL);
- dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 4");
// List
listnew = elm_list_add(layout);
evas_object_smart_callback_add(listnew, "selected", list_selected_cb, NULL);
elm_object_part_content_set(layout, "listnew", listnew);
elm_list_go(listnew);
- dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 5");
// log_entry - text area for log
log_entry = elm_entry_add(layout);
evas_object_size_hint_align_set(log_entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
elm_object_part_content_set(layout, "log", log_entry);
- nf_it = elm_naviframe_item_push(nf, "Resource Container", NULL, NULL, scroller, NULL);
+ nf_it = elm_naviframe_item_push(nf, "Container Server", NULL, NULL, scroller, NULL);
elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
- dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 6");
}
elm_list_mode_set(list, ELM_LIST_COMPRESS);
evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
- // Main Menu Items Here
- elm_list_item_append(list, "Resource Container", NULL, NULL, containerCreateUI, nf);
-
elm_list_go(list);
// This button is set for devices which doesn't have H/W back key.
btn = elm_button_add(nf);
elm_object_style_set(btn, "naviframe/end_btn/default");
- nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
+ nf_it = elm_naviframe_item_push(nf, "Container Server", btn, NULL, list, NULL);
elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
+
+ containerCreateUI(nf);
}
typedef RemoteResourceUnit::UPDATE_MSG REMOTE_MSG;
DiscoverResourceUnit(const std::string &bundleId);
+ DiscoverResourceUnit(const DiscoverResourceUnit &other)=delete;
+ DiscoverResourceUnit& operator=( const DiscoverResourceUnit& rhs )=delete;
~DiscoverResourceUnit();
void startDiscover(DiscoverResourceInfo info, UpdatedCB updatedCB);
#include "payload_logging.h"
#include "oic_malloc.h"
+#include "octypes.h"
#include "rdpayload.h"
}
}
-OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload)
+OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload, const OCDevAddr *address)
{
OCResourceCollectionPayload *storeResource = (OCResourceCollectionPayload *)OICCalloc(1, sizeof(OCResourceCollectionPayload));
if (!storeResource)
return OC_STACK_NO_MEMORY;
}
- OC_LOG(DEBUG, TAG, "Storing Resources ... ");
+ OC_LOG_V(DEBUG, TAG, "Storing Resources for %s:%u", address->addr, address->port);
+
+ char rdPubAddr[MAX_ADDR_STR_SIZE];
+ snprintf(rdPubAddr, MAX_ADDR_STR_SIZE, "%s:%d", address->addr, address->port);
OCTagsPayload *tags = payload->tags;
- storeResource->tags = OCCopyTagsResources(tags->n.deviceName, tags->di.id, tags->baseURI,
- tags->bitmap, tags->port, tags->ins, tags->rts, tags->drel, tags->ttl);
+ storeResource->tags = OCCopyTagsResources(tags->n.deviceName, tags->di.id, rdPubAddr,
+ tags->bitmap, address->port, tags->ins, tags->rts, tags->drel, tags->ttl);
if (!storeResource->tags)
{
OC_LOG(ERROR, TAG, "Failed allocating memory for tags.");
* Stores the publish resources.
*
* @param payload RDPublish payload sent from the remote device.
+ * @param address The address of the device publishing resources.
*
* @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR in case of error.
*/
-OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload);
+OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload, const OCDevAddr *address);
#ifdef __cplusplus
}
goto no_memory;
}
+ OCTagsLog(DEBUG, rdPayload->rdPublish->tags);
+ OCLinksLog(DEBUG, rdPayload->rdPublish->setLinks);
+
OCDevAddr rdAddr = { 0 };
OICStrcpy(rdAddr.addr, MAX_ADDR_STR_SIZE, addr);
rdAddr.port = port;
OCRDPayload *payload = (OCRDPayload *)ehRequest->payload;
if (payload && payload->rdPublish)
{
- OCRDStorePublishedResources(payload->rdPublish);
+ OCRDStorePublishedResources(payload->rdPublish, &ehRequest->devAddr);
}
OCRDPayload *rdPayload = OCRDPayloadCreate();
auto res = getResource(env, obj);
VERIFY_NO_EXC(env);
- res->setGetRequestHandler(std::bind(onGetRequest, std::placeholders::_1, std::placeholders::_2,
- JavaGlobalRef{ env, listenerObj }));
+ if (listenerObj)
+ {
+ res->setGetRequestHandler(std::bind(onGetRequest, std::placeholders::_1, std::placeholders::_2,
+ JavaGlobalRef{ env, listenerObj }));
+ }
+ else
+ {
+ res->setGetRequestHandler({ });
+ }
}
JNIEXPORT void JNICALL
auto res = getResource(env, obj);
VERIFY_NO_EXC(env);
- res->setSetRequestHandler(std::bind(onSetRequest, std::placeholders::_1, std::placeholders::_2,
- JavaGlobalRef{ env, listenerObj }));
+ if (listenerObj)
+ {
+ res->setSetRequestHandler(std::bind(onSetRequest, std::placeholders::_1,
+ std::placeholders::_2, JavaGlobalRef{ env, listenerObj }));
+ }
+ else
+ {
+ res->setSetRequestHandler({ });
+ }
}
JNIEXPORT void JNICALL
return true;
case REQUEST_LIGHT:
resourceType = LIGHT;
- defaultKey = "Light";
+ defaultKey = "Brightness";
return true;
default :
std::cout << "Invalid input, please try again" << std::endl;
#ifndef RECLIENT_H__
#define RECLIENT_H__
+#include <string>
+
typedef void(*ClientMenuHandler)();
typedef int ReturnValue;
+const std::string TEMPERATURE_URI = "/a/TempSensor";
+const std::string LIGHT_URI = "/a/light";
+const std::string TEMPERATURE_RT = "oic.r.temperaturesensor";
+const std::string LIGHT_RT = "oic.r.light";
+const std::string TEMPERATURE_AK = "Temperature";
+const std::string LIGHT_AK = "Brightness";
+
+void client_cb(void *data);
+
void *showClientAPIs(void *data);
#endif // RECLIENT_H__
\ No newline at end of file
#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.resampleclient/res/ui_controls.edj"
-void client_cb(void *data, Evas_Object *obj, void *event_info);
+void discoverTempSensor(void *data, Evas_Object *obj, void *event_info);
+
+void discoverLight(void *data, Evas_Object *obj, void *event_info);
#endif // RECLIENTMAIN_H__
\ No newline at end of file
#include<iostream>
#include "reclientmain.h"
-
#include "RCSDiscoveryManager.h"
#include "RCSRemoteResourceObject.h"
#include "RCSResourceAttributes.h"
#include "RCSAddress.h"
-
#include "OCPlatform.h"
# define checkResource nullptr == resource?false:true
using namespace OC;
using namespace OIC::Service;
-constexpr int CORRECT_INPUT = 1;
-constexpr int INCORRECT_INPUT = 2;
-constexpr int QUIT_INPUT = 3;
-
std::shared_ptr<RCSRemoteResourceObject> resource;
std::vector<RCSRemoteResourceObject::Ptr> resourceList;
std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
-const std::string defaultKey = "Temperature";
-const std::string resourceType = "oic.r.temperaturesensor";
+std::string g_resourceUri;
+std::string g_resourceType;
+std::string g_attributeKey;
static Evas_Object *log_entry = NULL;
static Evas_Object *list = NULL;
resourceList.push_back(foundResource);
- if ("/a/TempSensor" == resourceURI)
+ if (g_resourceUri == resourceURI)
resource = foundResource;
}
}
}
-static void setAttributeToRemoteServer(int setTemperature)
+static void setAttributeToRemoteServer(int setValue)
{
- string key = "Temperature";
string logMessage = "";
RCSResourceAttributes setAttribute;
- setAttribute[key] = setTemperature;
+ setAttribute[g_attributeKey] = setValue;
if (checkResource)
{
{
try
{
- logMessage = logMessage + "KEY:" + defaultKey.c_str() + "<br>";
- int attrValue = resource->getCachedAttribute(defaultKey).get< int >();
+ logMessage = logMessage + "KEY:" + g_attributeKey.c_str() + "<br>";
+ int attrValue = resource->getCachedAttribute(g_attributeKey).get< int >();
logMessage = logMessage + "VALUE:" + to_string(attrValue) + "<br>";
}
catch (const RCSBadRequestException &e)
while (!discoveryTask)
{
+ resourceList.clear();
+ resource = nullptr;
try
{
discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
- RCSAddress::multicast(), resourceType, &onResourceDiscovered);
+ RCSAddress::multicast(), g_resourceType, &onResourceDiscovered);
}
catch (const RCSPlatformException &e)
{
else
{
discoveryTask->cancel();
+ discoveryTask = nullptr;
logMessage += "Discovery canceled <br>";
{
temperature_popup_fields *popup_fields = (temperature_popup_fields *)data;
Evas_Object *entry = popup_fields->entry;
- const char *temperatureString = elm_entry_entry_get(entry);
+ const char *attributeString = elm_entry_entry_get(entry);
// Remove white spaces(if any) at the beginning
int beginning = 0;
- while (temperatureString[beginning] == ' ')
+ while (attributeString[beginning] == ' ')
{
(beginning)++;
}
- int len = strlen(temperatureString);
- if (NULL == temperatureString || 1 > len)
+ int len = strlen(attributeString);
+ if (NULL == attributeString || 1 > len)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL Temperature Value");
- string logMessage = "Temperature Cannot be NULL<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL attribute Value");
+ string logMessage = g_attributeKey + " Cannot be NULL<br>";
logMessage += "----------------------<br>";
dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
}
else
{
- int temperate = atoi(temperatureString);
- string tempString(temperatureString);
- setAttributeToRemoteServer(temperate);
- dlog_print(DLOG_INFO, LOG_TAG, "#### Temperature to set : %d", temperate);
+ int attributeValue = atoi(attributeString);
+ string attrString(attributeString);
+ setAttributeToRemoteServer(attributeValue);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Attribute to set : %d", attributeValue);
- string logMessage = "Temperature to set : " + tempString + "<br>";
+ string logMessage = g_attributeKey + " to set : " + attrString + "<br>";
logMessage += "----------------------<br>";
dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
}
static void
-list_scheduled_actionset_cb(void *data, Evas_Object *obj, void *event_info)
+list_get_attribute_value_cb(void *data, Evas_Object *obj, void *event_info)
{
Evas_Object *popup, *btn;
Evas_Object *nf = naviframe;
elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
eext_object_event_callback_add(popup, EEXT_CALLBACK_BACK, eext_popup_back_cb, NULL);
evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
- elm_object_part_text_set(popup, "title,text", "Enter the temperature");
+ if (LIGHT_RT == g_resourceType)
+ {
+ elm_object_part_text_set(popup, "title,text", "Enter the brightness");
+ }
+ else
+ {
+ elm_object_part_text_set(popup, "title,text", "Enter the temperature");
+ }
layout = elm_layout_add(popup);
elm_layout_file_set(layout, ELM_DEMO_EDJ, "popup_datetime_text");
evas_object_size_hint_weight_set(entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
eext_entry_selection_back_event_allow_set(entry, EINA_TRUE);
- elm_object_part_text_set(entry, "elm.guide", "in degree celsius");
+ if (LIGHT_RT == g_resourceType)
+ {
+ elm_object_part_text_set(entry, "elm.guide", "RANGE (0 - 50)");
+ }
+ else
+ {
+ elm_object_part_text_set(entry, "elm.guide", "in degree celsius");
+ }
elm_entry_input_panel_layout_set(entry, ELM_INPUT_PANEL_LAYOUT_NUMBER);
elm_object_part_content_set(layout, "elm.swallow.content", entry);
getAttributeFromRemoteServer, NULL);
elm_list_item_append(list, "4. Set Attribute", NULL, NULL,
- list_scheduled_actionset_cb, NULL);
+ list_get_attribute_value_cb, NULL);
elm_list_item_append(list, "5. Start Caching - No update", NULL, NULL,
startCachingWithoutCallback, NULL);
return EINA_TRUE;
}
-// Method to be called when the Group APIs UI Button is selected
-void client_cb(void *data, Evas_Object *obj, void *event_info)
+void client_cb(void *data)
{
Evas_Object *layout;
Evas_Object *scroller;
nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", NULL, NULL, scroller, NULL);
elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
}
+
+void discoverTempSensor(void *data, Evas_Object *obj, void *event_info)
+{
+ g_resourceUri = TEMPERATURE_URI;
+ g_resourceType = TEMPERATURE_RT;
+ g_attributeKey = TEMPERATURE_AK;
+
+ client_cb(data);
+}
+
+void discoverLight(void *data, Evas_Object *obj, void *event_info)
+{
+ g_resourceUri = LIGHT_URI;
+ g_resourceType = LIGHT_RT;
+ g_attributeKey = LIGHT_AK;
+
+ client_cb(data);
+}
evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
// Main Menu Items Here
+ elm_list_item_append(list, "Discover Temperature Sensor Resource", NULL, NULL, discoverTempSensor,
+ nf);
+
+ elm_list_item_append(list, "Discover Light Resource", NULL, NULL, discoverLight, nf);
+
elm_list_go(list);
// This button is set for devices which doesn't have H/W back key.
elm_object_style_set(btn, "naviframe/end_btn/default");
nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
-
- client_cb(nf, NULL, NULL);
}
#ifdef LOG_TAG
#undef LOG_TAG
#endif
-#define LOG_TAG "reservermain"
+#define LOG_TAG "reserver"
#if !defined(PACKAGE)
#define PACKAGE "org.tizen.resampleserver"
#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.resampleserver/res/ui_controls.edj"
-void serverCreateUI(void *data, Evas_Object *obj, void *event_info);
+void temperatureResource(void *data, Evas_Object *obj, void *event_info);
+
+void lightResource(void *data, Evas_Object *obj, void *event_info);
#endif // REMAIN_H__
\ No newline at end of file
constexpr int PRESENCE_ON = 1;
constexpr int PRESENCE_OFF = 2;
-std::string resourceUri = "/a/TempSensor";
-std::string resourceType = "oic.r.temperaturesensor";
-std::string resourceInterface = "oic.if.";
-std::string attributeKey = "Temperature";
-int isPresenceOn = PRESENCE_ON;
+const std::string TEMPERATURE_URI = "/a/TempSensor";
+const std::string LIGHT_URI = "/a/light";
+const std::string TEMPERATURE_RT = "oic.r.temperaturesensor";
+const std::string LIGHT_RT = "oic.r.light";
+const std::string TEMPERATURE_AK = "Temperature";
+const std::string LIGHT_AK = "Brightness";
+const std::string RESOURCE_INTERFACE = "oic.if.";
enum class Control
{
void start_server_cb(void *data, Evas_Object *obj, void *event_info);
-void *showGroupAPIs(void *data);
+void *showAPIs(void *data);
#endif // RESERVER_H__
\ No newline at end of file
evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
// Main Menu Items Here
- elm_list_item_append(list, "Start Temperature Sensor", NULL, NULL, serverCreateUI, nf);
+ elm_list_item_append(list, "Start Temperature Sensor Resource", NULL, NULL, temperatureResource,
+ nf);
+
+ elm_list_item_append(list, "Start Light Resource", NULL, NULL, lightResource, nf);
elm_list_go(list);
using namespace OC;
using namespace OIC::Service;
+# define checkServer NULL!=server?true:false
+
RCSResourceObject::Ptr server;
+static bool serverStarted = false;
static bool serverCallback = false;
+int isPresenceOn = PRESENCE_ON;
-# define checkServer NULL!=server?true:false
+std::string g_resourceUri;
+std::string g_resourceType;
+std::string g_attributeKey;
static Evas_Object *log_entry = NULL;
static Evas_Object *list = NULL;
static void onDestroy()
{
- server = NULL;
string logMessage = "SERVER DESTROYED";
- if(isPresenceOn == PRESENCE_ON)
+ if(true == serverStarted)
{
- OCPlatform::stopPresence();
- }
+ server = nullptr;
+ if(isPresenceOn == PRESENCE_ON)
+ {
+ OCPlatform::stopPresence();
+ }
- dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
- ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
- &logMessage);
+ serverStarted = false;
+ }
}
//hander for get request (if developer choose second option for resource Creation)
elm_list_item_selected_set(it, EINA_FALSE);
}
-static void increaseTemp(void *data, Evas_Object *obj, void *event_info)
+static void increaseAttribute(void *data, Evas_Object *obj, void *event_info)
{
string logMessage = "";
if (checkServer)
{
RCSResourceObject::LockGuard lock(server);
- server->getAttributes()[attributeKey] = server->getAttribute<int>(attributeKey) + 10;
- string tempString = std::to_string(server->getAttribute<int>(attributeKey));
- logMessage = "TEMPERATURE CHANGED : " + tempString + "<br>";
+ server->getAttributes()[g_attributeKey] = server->getAttribute<int>(g_attributeKey) + 1;
+ string tempString = std::to_string(server->getAttribute<int>(g_attributeKey));
+ logMessage = g_attributeKey + " CHANGED : " + tempString + "<br>";
}
else
&logMessage);
}
-static void decreaseTemp(void *data, Evas_Object *obj, void *event_info)
+static void decreaseAttribute(void *data, Evas_Object *obj, void *event_info)
{
string logMessage = "";
if (checkServer)
{
RCSResourceObject::LockGuard lock(server);
- server->getAttributes()[attributeKey] = server->getAttribute<int>(attributeKey) - 10;
- string tempString = std::to_string(server->getAttribute<int>(attributeKey));
- logMessage = "TEMPERATURE CHANGED : " + tempString + "<br>";
+ server->getAttributes()[g_attributeKey] = server->getAttribute<int>(g_attributeKey) - 1;
+ string tempString = std::to_string(server->getAttribute<int>(g_attributeKey));
+ logMessage = g_attributeKey + " CHANGED : " + tempString + "<br>";
}
else
{
try
{
- server = RCSResourceObject::Builder(resourceUri, resourceType,
- resourceInterface).setDiscoverable(true).setObservable(true).build();
+ server = RCSResourceObject::Builder(g_resourceUri, g_resourceType,
+ RESOURCE_INTERFACE).setDiscoverable(true).setObservable(true).build();
}
catch (const RCSPlatformException &e)
{
server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
server->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
- server->setAttribute(attributeKey, DEFALUT_VALUE);
+ server->setAttribute(g_attributeKey, DEFALUT_VALUE);
string logMessage = "SERVER CREATED<br>";
dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
- ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showGroupAPIs, NULL);
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showAPIs, NULL);
}
static void
{
datetime_popup_fields *popup_fields = (datetime_popup_fields *)data;
Evas_Object *entry = popup_fields->entry;
- const char *temperatureString = elm_entry_entry_get(entry);
+ const char *attributeString = elm_entry_entry_get(entry);
// Remove white spaces(if any) at the beginning
string logMessage = "";
int beginning = 0;
- while (temperatureString[beginning] == ' ')
+ while (attributeString[beginning] == ' ')
{
(beginning)++;
}
- int len = strlen(temperatureString);
- if (NULL == temperatureString || 1 > len)
+ int len = strlen(attributeString);
+ if (NULL == attributeString || 1 > len)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL Temperature Value");
- logMessage = "Temperature Cannot be NULL<br>";
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL Value");
+ logMessage = g_attributeKey + "Cannot be NULL<br>";
}
else
{
if (checkServer)
{
RCSResourceObject::LockGuard lock(server);
- int temperate = atoi(temperatureString);
- server->getAttributes()[attributeKey] = temperate;
- logMessage = "TEMPERATURE CHANGED : " + to_string(server->getAttribute<int>
- (attributeKey)) + "<br>";
+ int attributeInt = atoi(attributeString);
+ server->getAttributes()[g_attributeKey] = attributeInt;
+ logMessage = g_attributeKey + " CHANGED : " + to_string(server->getAttribute<int>
+ (g_attributeKey)) + "<br>";
}
else
{
}
static void
-list_get_temperaure_cb(void *data, Evas_Object *obj, void *event_info)
+list_get_attribute_cb(void *data, Evas_Object *obj, void *event_info)
{
Evas_Object *popup, *btn;
Evas_Object *nf = naviframe;
elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
eext_object_event_callback_add(popup, EEXT_CALLBACK_BACK, eext_popup_back_cb, NULL);
evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
- elm_object_part_text_set(popup, "title,text", "Enter the temperature");
+ if (LIGHT_RT == g_resourceType)
+ {
+ elm_object_part_text_set(popup, "title,text", "Enter the brightness");
+ }
+ else
+ {
+ elm_object_part_text_set(popup, "title,text", "Enter the temperature");
+ }
layout = elm_layout_add(popup);
elm_layout_file_set(layout, ELM_DEMO_EDJ, "popup_datetime_text");
evas_object_size_hint_weight_set(entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
eext_entry_selection_back_event_allow_set(entry, EINA_TRUE);
- elm_object_part_text_set(entry, "elm.guide", "in degree celsius");
+ if (LIGHT_RT == g_resourceType)
+ {
+ elm_object_part_text_set(entry, "elm.guide", "RANGE (0 - 50)");
+ }
+ else
+ {
+ elm_object_part_text_set(entry, "elm.guide", "in degree celsius");
+ }
+
elm_entry_input_panel_layout_set(entry, ELM_INPUT_PANEL_LAYOUT_NUMBER);
elm_object_part_content_set(layout, "elm.swallow.content", entry);
evas_object_show(popup);
}
-void *showGroupAPIs(void *data)
+void *showAPIs(void *data)
{
// Add items to the list only if the list is empty
const Eina_List *eina_list = elm_list_items_get(list);
int count = eina_list_count(eina_list);
if (!count)
{
- elm_list_item_append(list, "1. Increase Temperature", NULL, NULL,
- increaseTemp, NULL);
+ if (LIGHT_RT == g_resourceType)
+ {
+ elm_list_item_append(list, "1. Increase Brightness", NULL, NULL,
+ increaseAttribute, NULL);
+
+ elm_list_item_append(list, "2. Decrease Brightness", NULL, NULL,
+ decreaseAttribute, NULL);
- elm_list_item_append(list, "2. Decrease Temperature", NULL, NULL,
- decreaseTemp, NULL);
+ elm_list_item_append(list, "3. Set Brightness", NULL, NULL,
+ list_get_attribute_cb, NULL);
+ }
+ else
+ {
+ elm_list_item_append(list, "1. Increase Temperature", NULL, NULL,
+ increaseAttribute, NULL);
+
+ elm_list_item_append(list, "2. Decrease Temperature", NULL, NULL,
+ decreaseAttribute, NULL);
+
+ elm_list_item_append(list, "3. Set Temperature", NULL, NULL,
+ list_get_attribute_cb, NULL);
+ }
- elm_list_item_append(list, "3. Set Temperature", NULL, NULL,
- list_get_temperaure_cb, NULL);
elm_list_go(list);
}
void start_server(void *data, Evas_Object *obj, void *event_info)
{
server = NULL;
+ serverStarted = true;
string logMessage = "SERVER WITHOUT CALLBACK<br>";
serverCallback = false;
void start_server_cb(void *data, Evas_Object *obj, void *event_info)
{
server = NULL;
+ serverStarted = true;
string logMessage = "SERVER WITH CALLBACK<br>";
serverCallback = true;
&logMessage);
}
+
+void temperatureResource(void *data, Evas_Object *obj, void *event_info)
+{
+ g_resourceUri = TEMPERATURE_URI;
+ g_resourceType = TEMPERATURE_RT;
+ g_attributeKey = TEMPERATURE_AK;
+
+ serverCreateUI(data, NULL, NULL);
+}
+
+void lightResource(void *data, Evas_Object *obj, void *event_info)
+{
+ g_resourceUri = LIGHT_URI;
+ g_resourceType = LIGHT_RT;
+ g_attributeKey = LIGHT_AK;
+
+ serverCreateUI(data, NULL, NULL);
+}
typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int)>
SetCallback;
+ typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int)>
+ PutCallback;
+
typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int, int)>
ObserveCallback;
virtual void requestGet(GetCallback) = 0;
virtual void requestSet(const RCSResourceAttributes&, SetCallback) = 0;
+ virtual void requestPut(const RCSResourceAttributes&, PutCallback) = 0;
virtual void requestObserve(ObserveCallback) = 0;
virtual void cancelObserve() = 0;
{
using namespace std::placeholders;
+ typedef OCStackResult(BaseResource::*PostFunc)(
+ const OC::OCRepresentation&,
+ const OC::QueryParamsMap&, OC::PostCallback);
+
+ invokeOC(m_baseResource, static_cast< PostFunc >(&BaseResource::post),
+ ResourceAttributesConverter::toOCRepresentation(attrs),
+ OC::QueryParamsMap{ },
+ std::bind(safeCallback< SetCallback >, WeakFromThis(),
+ std::move(callback), _1, _2, _3));
+ }
+
+ void requestPut(const RCSResourceAttributes& attrs, PutCallback callback)
+ {
+ using namespace std::placeholders;
+
typedef OCStackResult(BaseResource::*PutFunc)(
const OC::OCRepresentation&,
const OC::QueryParamsMap&, OC::PutCallback);
invokeOC(m_baseResource, static_cast< PutFunc >(&BaseResource::put),
ResourceAttributesConverter::toOCRepresentation(attrs),
OC::QueryParamsMap{ },
- std::bind(safeCallback< SetCallback >, WeakFromThis(),
+ std::bind(safeCallback< PutCallback >, WeakFromThis(),
std::move(callback), _1, _2, _3));
}
invokeOC(m_baseResource, static_cast< ObserveFunc >(&BaseResource::observe),
OC::ObserveType::ObserveAll, OC::QueryParamsMap{ },
std::bind(safeObserveCallback, WeakFromThis(),
- std::move(callback), _1, _2, _3, _4));
+ std::move(callback), _1, _2, _3, _4));
}
void cancelObserve()
virtual OCStackResult put(
const OC::OCRepresentation&, const OC::QueryParamsMap&, OC::PutCallback) = 0;
+ virtual OCStackResult post(
+ const OC::OCRepresentation&, const OC::QueryParamsMap&, OC::PostCallback) = 0;
+
virtual OCStackResult observe(
OC::ObserveType, const OC::QueryParamsMap&, OC::ObserveCallback) = 0;
return handleRequestGet(request);
}
- if (request->getRequestType() == "PUT")
+ if (request->getRequestType() == "POST")
{
return handleRequestSet(request);
}
simulator_env.AppendUnique(CPPPATH = [
'../../resource/include/',
'../../resource/csdk/stack/include',
- '../../resource/csdk/ocrandom/include',
+ '../../resource/c_common/ocrandom/include',
'../../resource/csdk/logger/include',
'../../resource/oc_logger/include',
'./ramlparser/raml',
void write(std::string time, ILogger::Level level, std::string message)
{
std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " "
- << message;
+ << message;
}
};
std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
class SimLightResource
{
public:
- void startTest(std::string &configPath)
+ void startTest()
{
printMenu();
bool cont = true;
switch (choice)
{
- case 1 : simulateResource(configPath); break;
+ case 1 : simulateResource(); break;
case 2 : displayResource(); break;
- case 3 :
- try
- {
- deleteResource();
- }
- catch (InvalidArgsException &e)
- {
- std::cout << "InvalidArgsException occured [code : " << e.code() <<
- " Detail: " << e.what() << "]" << std::endl;
- }
- break;
+ case 3 : deleteResource(); break;
case 4 : updateAttributePower(); break;
case 5 : updateAttributeIntensity(); break;
case 6 : automateResourceUpdate(); break;
const SimulatorResourceModel &resModel)
{
std::cout << "[callback] Resource model is changed URI: " << uri.c_str()
- << " Count : " << resModel.size() << std::endl;
+ << " Count : " << resModel.size() << std::endl;
std::cout << "#### Modified attributes are ####" << std::endl;
for (auto & attribute : resModel.getAttributes())
{
std::cout << attribute.second.getName() << " : "
- << attribute.second.valueToString().c_str() << std::endl;
+ << attribute.second.valueToString().c_str() << std::endl;
}
std::cout << "########################" << std::endl;
}
- void simulateResource(std::string &configPath)
+ void simulateResource()
{
SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
&SimLightResource::onResourceModelChanged, this, std::placeholders::_1,
try
{
+ std::string configPath;
+ std::cout << "Enter RAML path: ";
+ std::cin>>configPath;
SimulatorResourceServerSP resource =
- SimulatorManager::getInstance()->createResource(configPath, callback);
+ SimulatorManager::getInstance()->createResource(configPath, callback);
m_resources.push_back(resource);
std::cout << "Resource created successfully! URI= " << resource->getURI().c_str()
- << std::endl;
+ << std::endl;
}
catch (InvalidArgsException &e)
{
std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
- << e.what() << "]" << std::endl;
+ << e.what() << "]" << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code() << " Detail: "
- << e.what() << "]" << std::endl;
+ << e.what() << "]" << std::endl;
}
}
{
SimulatorManager::getInstance()->deleteResource(resourceType);
std::cout << "Resources of type \"" << resourceType << "\"" <<
- " deleted successfully! " << std::endl;
+ " deleted successfully! " << std::endl;
std::vector<SimulatorResourceServerSP>::iterator ite = m_resources.begin();
while (ite != m_resources.end())
{
catch (InvalidArgsException &e)
{
std::cout << "InvalidArgsException occured [code : " << e.code()
- << " Detail: " << e.what() << "]" << std::endl;
+ << " Detail: " << e.what() << "]" << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code()
- << " Detail: " << e.what() << "]" << std::endl;
+ << " Detail: " << e.what() << "]" << std::endl;
}
} break;
}
std::cout << "Setting the new values from allowed values list to power attribute" <<
- std::endl;
+ std::endl;
// Update all possible values from allowed values
for (int index = 0; index < allowedValuesSize; index++)
{
}
std::cout << "Setting the new values from allowed values list to intensity attribute"
- << std::endl;
+ << std::endl;
// Update all possible values from allowed values
for (int index = min; index <= max; index++)
{
// Attributes
SimulatorResourceModel resModel = resource->getModel();
std::map<std::string, SimulatorResourceModel::Attribute> attributes =
- resModel.getAttributes();
+ resModel.getAttributes();
std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
for (auto & attribute : attributes)
{
const int id)
{
std::cout << "Update automation is completed [URI: " << uri.c_str()
- << " AutomationID: " << id << "] ###" << std::endl;
+ << " AutomationID: " << id << "] ###" << std::endl;
}
void automateResourceUpdate()
try
{
- int id = m_resources[index - 1]->startUpdateAutomation(type,
+ int id = m_resources[index - 1]->startUpdateAutomation(type, 500,
std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
- std::placeholders::_1, std::placeholders::_2));
+ std::placeholders::_1, std::placeholders::_2));
std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
- e.what() << "]" << std::endl;
+ e.what() << "]" << std::endl;
}
}
SimulatorResourceServerSP resource = m_resources[index - 1];
SimulatorResourceModel resModel = resource->getModel();
std::map<std::string, SimulatorResourceModel::Attribute> attributes =
- resModel.getAttributes();
+ resModel.getAttributes();
int size = 0;
for (auto & attribute : attributes)
{
int choice = -1;
std::cout << "Select the attribute which you want to automate for updation: " <<
- std::endl;
+ std::endl;
std::cin >> choice;
if (choice < 0 || choice > size)
{
type = AutomationType::RECURRENT;
std::cout << "Requesting attribute automation for " << attributeName.c_str() <<
- std::endl;
+ std::endl;
try
{
- int id = resource->startUpdateAutomation(attributeName, type,
+ int id = resource->startUpdateAutomation(attributeName, type, 500,
std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
- std::placeholders::_1, std::placeholders::_2));
+ std::placeholders::_1, std::placeholders::_2));
std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " <<
- e.what() << "]" << std::endl;
+ e.what() << "]" << std::endl;
}
}
if (!ids.size())
{
std::cout << "No automation operation is going on this resource right now!" <<
- std::endl;
+ std::endl;
return;
}
std::ostringstream out;
out << "ID: " << (int) observerInfo.id << std::endl;
out << " [address: " << observerInfo.address << " port: " << observerInfo.port
- << "]" << std::endl;
+ << "]" << std::endl;
std::cout << out.str();
}
for (auto & observerInfo : observersList)
{
std::cout << " ID : " << (int) observerInfo.id << " [address: " <<
- observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
+ observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
}
std::cout << "########################" << std::endl;
}
std::cout << "2. Set Logger" << std::endl;
std::cout << "3. Help" << std::endl;
std::cout << "0. Exit" << std::endl;
- std::cout <<
- "To set the Resource from RAML file, run the service provider with argument of Path of Raml File."
- << std::endl;
- std::cout <<
- "Example: ./simulator-server PATH-TO-RAML-FILE"
- << std::endl;
std::cout << "######################################" << std::endl;
}
int main(int argc, char *argv[])
{
- std::string configPath = "";
-
- if (argc == 2)
- {
- char *value = argv[1];
- configPath.append(value);
- }
- else
- {
- configPath = "";
- }
SimLightResource lightResource;
printMainMenu();
switch (choice)
{
- case 1: lightResource.startTest(configPath);
+ case 1: lightResource.startTest();
std::cout << "Welcome back to main menu !" << std::endl;
break;
case 2: setLogger(); break;
bool compare(Attribute &attribute);
- std::vector<ValueVariant> getAllowedValues();
+ std::vector<ValueVariant> getAllowedValues() const;
int getUpdateFrequencyTime() {return m_updateInterval;}
void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;}
ValueVariant &at(unsigned int index);
int size() const;
std::vector<std::string> toString() const;
- std::vector<ValueVariant> getValues();
+ std::vector<ValueVariant> getValues() const;
private:
std::vector<ValueVariant> m_values;
};
* @param attr - Attribute pointer
*
*/
- void addAttribute(const Attribute &attribute);
+ void addAttribute(const Attribute &attribute, bool overwrite = false);
/**
* API to set range of attribute value.
* @return ID representing update automation session.
* NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
*/
- virtual int startUpdateAutomation(AutomationType type,
+ virtual int startUpdateAutomation(AutomationType type, int updateInterval,
updateCompleteCallback callback) = 0;
/**
*
* @param attrName - Name of the attribute to be automated.
* @param type - Automation type.
+ * @param updateInterval -Interval time in milliseconds for attribute value update automation.
* @param callback - Callback to get notifiy when update automation is finished.
* @param id - Identifier for automation.
*
* NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
*/
virtual int startUpdateAutomation(const std::string &attrName, AutomationType type,
- updateCompleteCallback callback) = 0;
+ int updateInterval, updateCompleteCallback callback) = 0;
/**
* API to get the Ids of all ongoing resource update automation .
Bundle-ManifestVersion: 2
Bundle-Name: ClientControllerPlugin
Bundle-SymbolicName: ClientControllerPlugin;singleton:=true
-Bundle-Version: 0.1.0
+Bundle-Version: 1.0.0.qualifier
Bundle-Activator: oic.simulator.clientcontroller.Activator
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.InvalidArgsException;
import org.oic.simulator.ResourceAttribute;
import org.oic.simulator.ResourceAttribute.Range;
import org.oic.simulator.ResourceAttribute.Type;
// TODO: For debugging
if (null != attributeMap) {
RemoteResourceAttribute.printAttributes(attributeMap);
- System.out.println("Attributes found: ");
+ System.out.println("Attributes found: " + (null != attributeMap));
System.out.println("No of attributes: " + attributeMap.size());
resource.setResourceAttributesMap(attributeMap);
}
public boolean isResourceObserved(String resourceURI) {
- boolean observed;
+ boolean observed = false;
synchronized (observedResourceURIList) {
observed = observedResourceURIList.contains(resourceURI);
}
}
try {
resourceN.stopVerification(autoId);
- } catch (InvalidArgsException e) {
- Activator
- .getDefault()
- .getLogManager()
- .log(Level.ERROR.ordinal(),
- new Date(),
- "[" + e.getClass().getSimpleName() + "]"
- + e.code().toString() + "-"
- + e.message());
- return;
} catch (SimulatorException e) {
Activator
.getDefault()
*/
// TODO: Temporarily adding a resourceType for testing
- // resourceTypeCmb.add("oic.r.light");
+ // resourceTypeCmb.add("oic.r.light");
+ // Currently for standard resources we are using resource type as sample.light.
resourceTypeCmb.add("sample.light");
// By default, selecting the first item in the resourceType combo
import java.util.List;
import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.manager.ResourceManager;
import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
import oic.simulator.clientcontroller.utils.Constants;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Text;
/**
* This dialog is used for generating a POST request.
"Select" };
private final Integer[] attTblColWidth = { 200, 200, 50 };
- private ResourceManager resourceManager;
-
private List<PutPostAttributeModel> modelList = null;
-
+
public PostRequestDialog(Shell parentShell,
List<PutPostAttributeModel> modelList) {
super(parentShell);
this.modelList = modelList;
- resourceManager = Activator.getDefault().getResourceManager();
}
@Override
class AttributeValueEditor extends EditingSupport {
private final TableViewer viewer;
private final CellEditor editor;
-
+ private final Text txt;
public AttributeValueEditor(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
editor = new TextCellEditor(viewer.getTable());
+ txt = (Text)editor.getControl();
+ if(null != txt) {
+ txt.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ IStructuredSelection selection = (IStructuredSelection)AttributeValueEditor.this.viewer.getSelection();
+ PutPostAttributeModel att = (PutPostAttributeModel)selection.getFirstElement();
+ if(null == att) {
+ return;
+ }
+ String newValue = txt.getText();
+ if(null != newValue && !newValue.isEmpty()) {
+ att.setModified(true);
+ }
+ else {
+ att.setModified(false);
+ }
+ AttributeValueEditor.this.viewer.update(att, null);
+ }
+ });
+
+ }
}
@Override
// If there is a change, then its corresponding check box should be
// checked.
String newValue = String.valueOf(value);
- String actualValue = resourceManager.getAttributeValue(
- resourceManager.getCurrentResourceInSelection(),
- model.getAttName());
- if (newValue.equals(actualValue)) {
- model.setModified(false);
- } else {
- model.setModified(true);
- }
model.setAttValue(newValue);
viewer.update(element, null);
}
.createFromURL(bundle.getEntry("icons/button_pressed.PNG")));
// Resource icons based on the resource type
- r.put(Constants.OIC_R_LIGHT, ImageDescriptor.createFromURL(bundle
+ r.put(Constants.SAMPLE_LIGHT, ImageDescriptor.createFromURL(bundle
.getEntry("/icons/light_16x16.png")));
// Log View related icons
import org.eclipse.swt.graphics.Image;
import org.oic.simulator.IAutomation;
import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.InvalidArgsException;
import org.oic.simulator.ResourceAttribute;
import org.oic.simulator.ResourceAttribute.Range;
import org.oic.simulator.ResourceAttribute.Type;
}
public boolean isDisplayName(String displayName) {
- boolean exist;
+ boolean exist = false;
synchronized (displayNameMap) {
exist = displayNameMap.containsKey(displayName);
}
}
public String getCompleteUriFromDisplayName(String displayName) {
- String completeURI;
+ String completeURI = null;
synchronized (displayNameMap) {
completeURI = displayNameMap.get(displayName);
}
@Override
public void run() {
Map<String, SimulatorResource> resourceTypeMap;
- SimulatorResourceServer[] simulatorResourceServers;
+ SimulatorResourceServer[] simulatorResourceServers = null;
try {
simulatorResourceServers = SimulatorManager.createResource(
configFilePath, noOfInstances,
}
public List<String> getURIList() {
- List<String> list;
+ List<String> list = null;
synchronized (orderedResourceUriMap) {
Set<String> typeSet = orderedResourceUriMap.keySet();
List<String> typeList = Utility.convertSetToList(typeSet);
if (null == typeList || typeList.size() < 1) {
- return null;
+ return list;
}
list = new ArrayList<String>();
String attrName = attribute.getAttributeName();
try {
autoId = resourceServerN.startAttributeAutomation(attrName,
- autoType, automationListener);
+ autoType, autoUpdateInterval, automationListener);
} catch (SimulatorException e) {
Activator
.getDefault()
int autoId = -1;
try {
autoId = resourceServer.startResourceAutomation(
- AutomationType.NORMAL, automationListener);
+ AutomationType.NORMAL, 500, automationListener);
} catch (SimulatorException e) {
Activator
.getDefault()
public void shutdown() {
threadHandle.interrupt();
}
-}
+}
\ No newline at end of file
public static final String SPLIT_BY_DOT_PATTERN = "\\.";
- public static final String OIC_R_LIGHT = "oic.r.light";
+ public static final String SAMPLE_LIGHT = "sample.light";
}
\ No newline at end of file
if (deleteCategory == DeleteCategory.ALL) {
done = true;
} else if (deleteCategory == DeleteCategory.BY_TYPE) {
- int selectedItemIndex = resourceTypeCmb.getSelectionIndex();
- if (selectedItemIndex >= 0) {
- deleteCandidate = resourceTypeCmb.getItem(selectedItemIndex);
- if (null != deleteCandidate && deleteCandidate.length() > 0) {
- done = true;
- }
+ deleteCandidate = resourceTypeCmb.getText();
+ if (null != deleteCandidate && deleteCandidate.length() > 0) {
+ done = true;
}
} else if (deleteCategory == DeleteCategory.BY_URI) {
deleteCandidate = resourceUriTxt.getText();
return static_cast<jobject>(str);
}
-#if 0
// Boolean type value conversion
jobject operator ()(const bool &value) const
{
gSimulatorClassRefs.classBooleanCtor, value);
return result;
}
-
+#if 0
// SimulatorResourceModel::Attribute type value conversion
jobject operator ()(const SimulatorResourceModel::Attribute &value) const
{
jclass classObject;
jclass classInteger;
jclass classDouble;
+ jclass classBoolean;
jclass classString;
jclass classHashMap;
jclass classVector;
jmethodID classIntegerCtor;
jmethodID classDoubleCtor;
+ jmethodID classBooleanCtor;
jmethodID classHashMapCtor;
jmethodID classHashMapPut;
jmethodID classVectorCtor;
if (!m_env)
return nullptr;
- jmethodID constr = m_env->GetMethodID(gSimulatorClassRefs.classDeviceInfo, "<init>", "(V)V");
- if (constr)
+ jmethodID deviceInfoMId = m_env->GetMethodID(gSimulatorClassRefs.classDeviceInfo, "<init>", "(V)V");
+ if (!deviceInfoMId)
return nullptr;
- jobject jDeviceInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classDeviceInfo, constr);
- if (jDeviceInfo)
+ jobject jDeviceInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classDeviceInfo, deviceInfoMId);
+ if (!jDeviceInfo)
return nullptr;
setFieldValue(jDeviceInfo, "mName", deviceInfo.getName());
return JNI_ERR;
}
+ if (false == getClassRef(env, "java/lang/Boolean", gSimulatorClassRefs.classBoolean))
+ {
+ return JNI_ERR;
+ }
+
if (false == getClassRef(env, "java/lang/String", gSimulatorClassRefs.classString))
{
return JNI_ERR;
if (!gSimulatorClassRefs.classDoubleCtor)
return JNI_ERR;
+ gSimulatorClassRefs.classBooleanCtor= env->GetMethodID(gSimulatorClassRefs.classBoolean, "<init>",
+ "(Z)V");
+ if (!gSimulatorClassRefs.classBooleanCtor)
+ return JNI_ERR;
+
gSimulatorClassRefs.classHashMapCtor = env->GetMethodID(gSimulatorClassRefs.classHashMap, "<init>",
"()V");
if (!gSimulatorClassRefs.classHashMapCtor)
if (!jConfigPath)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
- "Configuration file path is empty!");
+ "Configuration file path is null!");
return;
}
}
}
+JNIEXPORT void JNICALL Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_dispose
+(JNIEnv *env, jobject thiz)
+{
+ JniSimulatorRemoteResource *resource = GetHandle<JniSimulatorRemoteResource>(env, thiz);
+ delete resource;
+}
\ No newline at end of file
Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
(JNIEnv *env, jobject thiz, jint jId);
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_dispose
+(JNIEnv *, jobject);
+
#ifdef __cplusplus
}
#endif
return;
}
+ if (!jvalue)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute value cannot be null!");
+ return;
+ }
+
SimulatorResourceModelSP resModelPtr;
resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
if (!resModelPtr)
return;
}
+ if (!jValue)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute value cannot be null!");
+ return;
+ }
+
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
if (!resource)
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
-(JNIEnv *env, jobject object, jint automationType, jobject listener)
+(JNIEnv *env, jobject object, jint automationType, jint updateInterval, jobject listener)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
if (!resource)
try
{
- automationId = resource->startUpdateAutomation(type, callback);
+ automationId = resource->startUpdateAutomation(type, updateInterval, callback);
}
catch (InvalidArgsException &e)
{
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
-(JNIEnv *env, jobject object, jstring attrName, jint automationType, jobject listener)
+(JNIEnv *env, jobject object, jstring attrName, jint automationType, jint updateInterval, jobject listener)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
if (!resource)
int automationId = -1;
try
{
- automationId = resource->startUpdateAutomation(attrNamePtr, type, callback);
+ automationId = resource->startUpdateAutomation(attrNamePtr, type, updateInterval, callback);
}
catch (InvalidArgsException &e)
{
}
std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->removeAttribute(str);
+ try
+ {
+ resource->removeAttribute(str);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return;
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ return;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
}
JNIEXPORT jobjectArray JNICALL
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
-(JNIEnv *, jobject, jint, jobject);
+(JNIEnv *, jobject, jint, jint, jobject);
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
-(JNIEnv *, jobject, jstring, jint, jobject);
+(JNIEnv *, jobject, jstring, jint, jint, jobject);
JNIEXPORT void JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation
protected void finalize() throws Throwable {
try {
dispose();
- } catch(Throwable t){
- throw t;
- } finally{
+ } finally {
super.finalize();
}
}
protected void finalize() throws Throwable {
try {
dispose();
- } catch(Throwable t){
- throw t;
- } finally{
+ } finally {
super.finalize();
}
}
* @param typeOfAutomation
* {@link AutomationType} indicating whether the automation is
* one-time or recursive.
+ * @param updateInterval
+ * Interval time in milliseconds for attribute value update automation.
* @param listener
* Listener to be notified when automation ends.
*
* This exception will be thrown for other errors.
*/
public int startResourceAutomation(AutomationType typeOfAutomation,
- IAutomation listener) throws InvalidArgsException,
+ int updateInterval, IAutomation listener) throws InvalidArgsException,
SimulatorException {
- return startResourceAutomation(typeOfAutomation.getValue(), listener);
+ return startResourceAutomation(typeOfAutomation.getValue(), updateInterval, listener);
}
/**
* @param typeOfAutomation
* {@link AutomationType} indicating whether the automation is
* one-time or recursive.
+ * @param updateInterval
+ * Interval time in milliseconds for attribute value update automation.
* @param listener
* Listener to be notified when automation ends.
*
* This exception will be thrown for other errors.
*/
public int startAttributeAutomation(String attrName,
- AutomationType typeOfAutomation, IAutomation listener)
+ AutomationType typeOfAutomation, int updateInterval,
+ IAutomation listener)
throws InvalidArgsException, SimulatorException {
return startAttributeAutomation(attrName, typeOfAutomation.getValue(),
- listener);
+ updateInterval, listener);
}
/**
SimulatorException;
private native int startResourceAutomation(int typeOfAutomation,
- IAutomation listener) throws InvalidArgsException,
+ int updateInterval, IAutomation listener) throws InvalidArgsException,
SimulatorException;
private native int startAttributeAutomation(String attrName,
- int typeOfAutomation, IAutomation listener)
+ int typeOfAutomation, int updateInterval, IAutomation listener)
throws InvalidArgsException, SimulatorException;
@Override
protected void finalize() throws Throwable {
try {
dispose();
- } catch(Throwable t){
- throw t;
- } finally{
+ } finally {
super.finalize();
}
}
if (*it == reqValue)\r
break;\r
}\r
- if (m_required.end() == it)\r
+ if (m_required.end() != it)\r
{\r
m_required.push_back(reqValue);\r
}\r
if (*it == reqValue)\r
break;\r
}\r
- if (m_required.end() == it)\r
+ if (m_required.end() != it)\r
{\r
m_required.push_back(reqValue);\r
}\r
#include "attribute_generator.h"
-AttributeGenerator::AttributeGenerator(SimulatorResourceModel::Attribute &attribute)
+AttributeGenerator::AttributeGenerator(const SimulatorResourceModel::Attribute &attribute)
: m_name(attribute.getName()),
m_min(INT_MIN),
m_max(INT_MAX),
m_rangeIndex(-1),
- m_nextAllowedValueIndex(0),
- m_prevAllowedValueIndex(0),
+ m_allowedValueIndex(0),
m_hasRange(false),
m_hasAllowedValue(false)
{
{
m_hasAllowedValue = true;
}
- m_prevAllowedValueIndex = m_allowedValues.size();
}
}
return true;
}
- if (m_hasAllowedValue && m_nextAllowedValueIndex < m_allowedValues.size())
+ if (m_hasAllowedValue && m_allowedValueIndex < m_allowedValues.size())
{
return true;
}
}
else if (m_hasAllowedValue)
{
- attribute.setValue(m_allowedValues[m_nextAllowedValueIndex++]);
+ attribute.setValue(m_allowedValues[m_allowedValueIndex++]);
return true;
}
return false;
}
-bool AttributeGenerator::previous(SimulatorResourceModel::Attribute &attribute)
+SimulatorResourceModel::Attribute AttributeGenerator::current()
{
+ SimulatorResourceModel::Attribute attribute;
+
attribute.setName(m_name);
+ if (m_hasRange)
+ {
+ attribute.setValue(m_rangeIndex);
+ }
+ else if (m_hasAllowedValue)
+ {
+ attribute.setValue(m_allowedValues[m_allowedValueIndex]);
+ }
+
+ return attribute;
+}
+void AttributeGenerator::reset()
+{
if (m_hasRange)
{
- attribute.setValue(m_rangeIndex - 1);
- return true;
+ m_rangeIndex = m_min;
}
else if (m_hasAllowedValue)
{
- attribute.setValue(m_allowedValues[m_prevAllowedValueIndex - 1]);
+ m_allowedValueIndex = 0;
+ }
+}
+
+AttributeCombinationGen::AttributeCombinationGen(
+ const std::vector<SimulatorResourceModel::Attribute> &attributes)
+{
+ for (auto &attr : attributes)
+ {
+ AttributeGenerator attrGen(attr);
+ m_attrGenList.push_back(attr);
+ }
+
+ m_index = -1;
+}
+
+bool AttributeCombinationGen::next(SimulatorResourceModel &resModel)
+{
+ if (!m_attrGenList.size())
+ {
+ return false;
+ }
+
+ std::lock_guard<std::mutex> lock(m_lock);
+
+ // This block will execute for only first time
+ if (-1 == m_index)
+ {
+ for (int index = 0; index < m_attrGenList.size(); index++)
+ {
+ // Add the attribute on resource model
+ addAttributeToModel(index);
+ }
+
+ m_index = m_attrGenList.size() - 1;
+ resModel = m_resModel;
+ return true;
+ }
+
+ // Get the next attribute from statck top element
+ if (m_attrGenList[m_index].hasNext())
+ {
+ addAttributeToModel(m_index);
+ resModel = m_resModel;
+ return true;
+ }
+ else
+ {
+ for (int index = m_index; index >= 0; index--)
+ {
+ if (!m_attrGenList[index].hasNext())
+ {
+ if (!index)
+ return false;
+
+ m_attrGenList[index].reset();
+ addAttributeToModel(index);
+ }
+ else
+ {
+ addAttributeToModel(index);
+ break;
+ }
+ }
+
+ resModel = m_resModel;
return true;
}
return false;
}
+void AttributeCombinationGen::addAttributeToModel(int index)
+{
+ SimulatorResourceModel::Attribute attribute;
+ m_attrGenList[index].next(attribute);
+ m_resModel.addAttribute(attribute, true);
+}
class AttributeGenerator
{
public:
- AttributeGenerator(SimulatorResourceModel::Attribute &attribute);
+ AttributeGenerator(const SimulatorResourceModel::Attribute &attribute);
bool hasNext();
bool next(SimulatorResourceModel::Attribute &attribute);
- bool previous(SimulatorResourceModel::Attribute &attribute);
+ SimulatorResourceModel::Attribute current();
void reset();
private:
std::string m_name;
- SimulatorResourceModel::Attribute::ValueType m_type;
int m_min;
int m_max;
int m_rangeIndex;
- int m_nextAllowedValueIndex;
- int m_prevAllowedValueIndex;
+ int m_allowedValueIndex;
bool m_hasRange;
bool m_hasAllowedValue;
std::vector<SimulatorResourceModel::Attribute::ValueVariant> m_allowedValues;
};
+class AttributeCombinationGen
+{
+ public:
+ AttributeCombinationGen(const std::vector<SimulatorResourceModel::Attribute> &attributes);
+ bool next(SimulatorResourceModel &resModel);
+
+ private:
+ void addAttributeToModel(int index);
+
+ std::mutex m_lock;
+ std::vector<AttributeGenerator> m_attrGenList;
+ int m_index;
+ SimulatorResourceModel m_resModel;
+};
+
#endif
OC_LOG(DEBUG, TAG, "Sending OP_START event");
m_callback(m_id, OP_START);
- // Create attribute generator for value manipulation
- std::vector<AttributeGenerator> attributeGenList;
+ // Create attribute combination generator for generating resource model
+ // with different attribute values
+ std::vector<SimulatorResourceModel::Attribute> attributes;
for (auto &attributeElement : m_rep->getAttributes())
- attributeGenList.push_back(AttributeGenerator(attributeElement.second));
+ {
+ attributes.push_back(attributeElement.second);
+ }
- if (!attributeGenList.size())
+ if (!attributes.size())
{
OC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
return;
}
- bool hasNext = false;
-
do
{
- if (!m_stopRequested)
+ if (m_stopRequested)
{
- // Get the next possible queryParameter
- std::map<std::string, std::string> queryParam = m_queryParamGen.next();
-
- while (true)
- {
- SimulatorResourceModelSP repModel(new SimulatorResourceModel);
- for (auto & attributeGen : attributeGenList)
- {
- if (attributeGen.hasNext())
- {
- SimulatorResourceModel::Attribute attribute;
- if (true == attributeGen.next(attribute))
- repModel->addAttribute(attribute);
-
- hasNext = true;
- }
- else
- {
- SimulatorResourceModel::Attribute attribute;
- if (true == attributeGen.previous(attribute))
- repModel->addAttribute(attribute);
- }
- }
-
- if (hasNext)
- {
- // Send the request
- m_requestSender->sendRequest(queryParam, repModel,
- std::bind(&PUTRequestGenerator::onResponseReceived, this,
- std::placeholders::_1, std::placeholders::_2), true);
-
- m_requestCnt++;
- hasNext = false;
- continue;
- }
- else
- {
- break;
- }
- }
+ break;
+ }
+
+ // Get the next possible queryParameter
+ std::map<std::string, std::string> queryParam = m_queryParamGen.next();
+
+ AttributeCombinationGen attrCombGen(attributes);
+
+ // Get the new model from attribute combination generator
+ SimulatorResourceModel resModel;
+ while (!m_stopRequested && attrCombGen.next(resModel))
+ {
+ SimulatorResourceModelSP repModel(new SimulatorResourceModel(resModel));
+
+ // Send the request
+ m_requestSender->sendRequest(queryParam, repModel,
+ std::bind(&PUTRequestGenerator::onResponseReceived, this,
+ std::placeholders::_1, std::placeholders::_2), true);
+
+ m_requestCnt++;
}
}
while (m_queryParamGen.hasNext());
if (m_getRequestSender)
{
return m_autoRequestGenMngr->startOnGET(m_getRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
+ localCallback);
}
break;
if (m_putRequestSender)
{
return m_autoRequestGenMngr->startOnPUT(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
+ localCallback);
}
break;
if (m_postRequestSender)
{
return m_autoRequestGenMngr->startOnPOST(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
+ localCallback);
}
break;
{
if (path.empty())
{
- OC_LOG(ERROR, TAG, "Invalid path given for configuration !");
+ OC_LOG(ERROR, TAG, "Invalid path given for configuration!");
throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Empty path string!");
}
******************************************************************/
#include "simulator_resource_model.h"
+#include "simulator_exceptions.h"
+#include "logger.h"
#include "OCPlatform.h"
#include <sstream>
#include <boost/lexical_cast.hpp>
{
std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
= m_attrItem.getAllowedValues();
+ if(0 == values.size())
+ return true;
for (SimulatorResourceModel::Attribute::ValueVariant & val : values)
{
SimulatorResourceModel::Attribute::ValueVariant vVal = value;
{
std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
= m_attrItem.getAllowedValues();
+ if(0 == values.size())
+ return true;
for (SimulatorResourceModel::Attribute::ValueVariant & vVal : values)
{
std::string val = boost::get<std::string>(vVal);
}
std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::AllowedValues::getValues()
+SimulatorResourceModel::Attribute::AllowedValues::getValues() const
{
return m_values;
}
}
std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::getAllowedValues()
+SimulatorResourceModel::Attribute::getAllowedValues() const
{
return m_allowedValues.getValues();
}
return m_attributes;
}
-void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute)
+void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute, bool overwrite)
{
if (!attribute.getName().empty() &&
- m_attributes.end() == m_attributes.find(attribute.getName()))
+ (m_attributes.end() == m_attributes.find(attribute.getName()) || overwrite))
{
m_attributes[attribute.getName()] = attribute;
}
void SimulatorResourceModel::removeAttribute(const std::string &attrName)
{
- if (m_attributes.end() == m_attributes.find(attrName))
+ if (attrName.empty() || m_attributes.end() == m_attributes.find(attrName))
{
- return;
+ OC_LOG(ERROR, TAG, "Attribute name is empty or not found in model!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Attribute not found in model!");
}
m_attributes.erase(attrName);
attribute.setValue(attributeItem.getValue<double>());
if (attributeItem.type() == OC::AttributeType::String)
attribute.setValue(attributeItem.getValue<std::string>());
+ if (attributeItem.type() == OC::AttributeType::Boolean)
+ attribute.setValue(attributeItem.getValue<bool>());
attribute.setName(attributeItem.attrname());
resModel->m_attributes[attributeItem.attrname()] = attribute;
#include "resource_update_automation.h"
#include "simulator_resource_server_impl.h"
+#include "attribute_generator.h"
#include "simulator_exceptions.h"
#include "simulator_logger.h"
#include "logger.h"
SIM_LOG(ILogger::INFO, "Automation of " << m_attrName << " attribute is completed.");
}
- // Notify application through callback
+ // Notify application
if (m_callback)
m_callback(m_resource->getURI(), m_id);
: m_resource(resource),
m_type(type),
m_id(id),
+ m_stopRequested(false),
m_updateInterval(interval),
m_callback(callback),
- m_finishedCallback(finishedCallback) {}
+ m_finishedCallback(finishedCallback),
+ m_thread(nullptr) {}
void ResourceUpdateAutomation::start()
{
- m_resModel = m_resource->getModel();
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_resModel.getAttributes();
- if (0 == attributes.size())
+ SimulatorResourceModel resModel = m_resource->getModel();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributesTable =
+ resModel.getAttributes();
+ if (0 == attributesTable.size())
{
OC_LOG(ERROR, RTAG, "Resource has zero attributes!");
throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!");
}
- int id = 0;
- for (auto & attribute : attributes)
- {
- AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
- id, m_resource, attribute.first, m_type, m_updateInterval, nullptr,
- std::bind(&ResourceUpdateAutomation::finished, this, std::placeholders::_1)));
+ std::vector<SimulatorResourceModel::Attribute> attributes;
+ for (auto &attributeEntry : attributesTable)
+ attributes.push_back(attributeEntry.second);
- m_attrUpdationList[id++] = attributeAutomation;
- try
- {
- attributeAutomation->start();
- }
- catch (SimulatorException &e)
- {
- stop();
- throw;
- }
- }
+ m_thread = new std::thread(&ResourceUpdateAutomation::updateAttributes, this, attributes);
}
-void ResourceUpdateAutomation::finished(int id)
+void ResourceUpdateAutomation::stop()
{
- if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
- {
- m_attrUpdationList.erase(m_attrUpdationList.find(id));
- }
-
- if (!m_attrUpdationList.size())
- {
- // Notify application through callback
- if (m_callback)
- m_callback(m_resource->getURI(), m_id);
-
- if (m_finishedCallback)
- m_finishedCallback(m_id);
- }
+ m_stopRequested = true;
+ if (m_thread)
+ m_thread->join();
}
-void ResourceUpdateAutomation::stop()
+void ResourceUpdateAutomation::updateAttributes(
+ std::vector<SimulatorResourceModel::Attribute> attributes)
{
- // Stop all the attributes updation
- for (auto & attrAutomation : m_attrUpdationList)
+ SimulatorResourceServerImpl *resourceImpl =
+ dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
+
+ AttributeCombinationGen attrCombGen(attributes);
+ SimulatorResourceModel resModel;
+ while (!m_stopRequested && attrCombGen.next(resModel))
{
- (attrAutomation.second)->stop();
+ for (auto &attributeEntry : resModel.getAttributes())
+ {
+ resourceImpl->updateAttributeValue(attributeEntry.first, attributeEntry.second.getValue());
+ }
+
+ resourceImpl->notifyApp();
+ SLEEP_FOR(m_updateInterval);
}
- m_attrUpdationList.clear();
+ // Notify application
+ if (m_callback)
+ m_callback(m_resource->getURI(), m_id);
+
+ if (m_finishedCallback && !m_stopRequested)
+ m_finishedCallback(m_id);
}
+
void stop();
- void finished(int id);
-
private:
+ void updateAttributes(std::vector<SimulatorResourceModel::Attribute> attributes);
+
SimulatorResourceServer *m_resource;
AutomationType m_type;
int m_id;
+ bool m_stopRequested;
int m_updateInterval;
- SimulatorResourceModel m_resModel;
- std::map<int, AttributeUpdateAutomationSP> m_attrUpdationList;
updateCompleteCallback m_callback;
std::function<void (const int)> m_finishedCallback;
+ std::thread *m_thread;
};
typedef std::shared_ptr<ResourceUpdateAutomation> ResourceUpdateAutomationSP;
}
int SimulatorResourceServerImpl::startUpdateAutomation(AutomationType type,
- updateCompleteCallback callback)
+ int updateInterval, updateCompleteCallback callback)
{
if (!callback)
{
throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
}
- return m_updateAutomationMgr.startResourceAutomation(this, type, -1, callback);
+ return m_updateAutomationMgr.startResourceAutomation(this, type, updateInterval, callback);
}
int SimulatorResourceServerImpl::startUpdateAutomation(const std::string &attrName,
- AutomationType type,
+ AutomationType type, int updateInterval,
updateCompleteCallback callback)
{
if (!callback)
throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
}
- return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, -1, callback);
+ return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, updateInterval, callback);
}
std::vector<int> SimulatorResourceServerImpl::getResourceAutomationIds()
bool isObservable() const;
- int startUpdateAutomation(AutomationType type,
+ int startUpdateAutomation(AutomationType type, int updateInterval,
updateCompleteCallback callback);
int startUpdateAutomation(const std::string &attrName, AutomationType type,
- updateCompleteCallback callback);
+ int updateInterval, updateCompleteCallback callback);
std::vector<int> getResourceAutomationIds();
assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null);
}
+ /**
+ * model as null
+ */
+
+ public void testPut_N01() {
+ boolean result = true;
+ ListenerObject listenerObject = new ListenerObject();
+ PutListener putListener = new PutListener(lockObject, listenerObject);
+
+ try {
+ simulatorRemoteResource.put(null, null, putListener);
+ result = false;
+ } catch (Exception e1) {
+ result = true;
+ }
+
+ try {
+ lockObject.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ }
+
+ assertTrue(result && listenerObject.getRepresentation() == null && listenerObject.getuId() == null);
+ }
+
public void testPost_P01()
{
boolean result = true;
try
{
model.addAttributeInt("intensity", 8);
- //model.addAttributeString("power", "off");
listenerObject = new ListenerObject();
PostListener postListener = new PostListener(lockObject, listenerObject);
assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null);
}
+ /**
+ * Model is set to null
+ */
+
+ public void testPost_N01() {
+ boolean result = true;
+
+ lockObject = new CountDownLatch(1);
+
+ ListenerObject listenerObject = new ListenerObject();
+ PostListener postListener = new PostListener(lockObject, listenerObject);
+
+ try {
+ simulatorRemoteResource.post(null, null, postListener);
+ result = false;
+ } catch (Exception e1) {
+ result = true;
+ }
+
+ try {
+ lockObject.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ }
+
+ assertTrue(result && listenerObject.getRepresentation() == null && listenerObject.getuId() == null);
+ }
+
public void testGet_P01()
{
boolean result = true;
String resInterface = simulatorRemoteResource.getResourceInterfaces().get(0);
- if(resInterface == null)
- simulatorRemoteResource.get(resInterface, null, onGetListener);
+ if(resInterface != null)
+ simulatorRemoteResource.get(resInterface,null, onGetListener);
else
result = false;
}
{
String resInterface = simulatorRemoteResource.getResourceInterfaces().get(0);
- if(resInterface == null)
- simulatorRemoteResource.get(resInterface, null, null);
- else
- result = false;
+ if(resInterface != null)
+ {
+ simulatorRemoteResource.get( resInterface,null, null);
+ }
+
+ result = false;
}
catch(Exception e)
{
try
{
-
lockObject.await(100, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
System.loadLibrary("SimulatorManager");
System.loadLibrary("RamlParser");
- System.loadLibrary("YamlParser");
System.loadLibrary("oc");
System.loadLibrary("oc_logger");
System.loadLibrary("octbstack");
{
try
{
- simulatorResourceServer.addAttributeBoolean(KEY, true);
+ simulatorResourceServer.addAttributeBoolean(KEY, Boolean.parseBoolean("true"));
}
catch (Exception e)
{
e.printStackTrace();
}
- assertEquals(Boolean.parseBoolean(getValue(KEY) + ""), true);
+ assertEquals(Boolean.parseBoolean(getValue(KEY).toString() + ""), true);
}
public void testaddAttributeString_P01()
try
{
- simulatorResourceServer.addAttributeBoolean(KEY, true);
+ simulatorResourceServer.addAttributeBoolean(KEY, Boolean.parseBoolean("true"));
}
catch (Exception e)
{
try
{
- simulatorResourceServer.updateAttributeBoolean(KEY, false);
+ simulatorResourceServer.updateAttributeBoolean(KEY, Boolean.parseBoolean("false"));
}
catch (Exception e)
{
try
{
- lockObject.await(10,TimeUnit.SECONDS);
+ lockObject.await(15,TimeUnit.SECONDS);
}
catch (InterruptedException e)
{
{
result = false;
}
- assertTrue(result && id == -1);
+ assertTrue(!result && id == 0);
}
public void testStartAttributeAutomation_P01()
int id = 0;
try
{
- id = simulatorResourceServer.startAttributeAutomation(simulatorResourceServer.getModel().getAttributes().get(0).getName(),
+ simulatorResourceServer.addAttributeInteger(KEY, 10);
+ id = simulatorResourceServer.startAttributeAutomation(KEY,
AutomationType.NORMAL, automationListener);
}
catch (Exception e)
try
{
- lockObject.await(10, TimeUnit.SECONDS);
+ lockObject.await(05, TimeUnit.SECONDS);
}
catch (InterruptedException e)
{
}
- result = result && automationObject.getResourceURI() != null && automationObject.getAutomationId() != -1 && id != -1;
-
try
{
simulatorResourceServer.stopAutomation(id);
import java.util.concurrent.CountDownLatch;
import junit.framework.TestCase;
-import org.oic.simulator.DeviceInfo;
import org.oic.simulator.PlatformInfo;
import org.oic.simulator.SimulatorManager;
import org.oic.simulator.serviceprovider.SimulatorResourceServer;
private ResourceModelObject resourceModelObject;
private ResourceModelChangeListener resourceModelChangeListener;
- private DeviceInfo info;
- private PlatformInfo platformInfo;
static
{
System.loadLibrary("SimulatorManager");
- System.loadLibrary("RamlParser");
- System.loadLibrary("oc");
- System.loadLibrary("oc_logger");
- System.loadLibrary("octbstack");
}
@Override
SimulatorResourceServer[] simulatorResourceServers = null;
try
{
+ SimulatorManager.setDeviceInfo("test");
simulatorResourceServers = SimulatorManager.createResource(configPath, count, resourceModelChangeListener);
}
catch (Exception e)
boolean result = false;
SimulatorResourceServer[] simulatorResourceServers = null;
-
try
{
simulatorResourceServers = SimulatorManager.createResource(CONFIG_PATH, count, null);
assertTrue(simulatorResourceServers == null);
}
+ /**
+ * When count is set to -ve
+ */
+
+ public void testCreateResourceCount_N05()
+ {
+ int count = -10;
+
+ SimulatorResourceServer[] simulatorResourceServers = createResources(count);
+
+ assertTrue(simulatorResourceServers == null );
+ }
+
public void testDeleteResource_P01()
{
boolean result = true;
*/
public void testSetDeviceInfo_N01()
{
- SimulatorManager.setDeviceInfo("");
+ try
+ {
+ SimulatorManager.setDeviceInfo("");
+ }
+ catch(Exception e)
+ {
+ System.out.println("Exception hit");
+ }
+ }
+
+ /**
+ * checking for crash
+ * pass null
+ */
+ public void testSetDeviceInfo_N02()
+ {
+ try
+ {
+ SimulatorManager.setDeviceInfo(null);
+ }
+ catch(Exception e)
+ {
+ System.out.println("Exception hit");
+ }
+ }
+
+ public void testGetDeviceInfo_N01()
+ {
+ try
+ {
+ SimulatorManager.getDeviceInfo(null);
+ }
+ catch(Exception e)
+ {
+ System.out.println(" Exception hit");
+ }
}
/**
SimulatorManager.setPlatformInfo(platformInfo);
}
+
+ /**
+ * Checking for crash
+ */
+ public void testSetPlatformInfo_N01()
+ {
+ try
+ {
+ SimulatorManager.setPlatformInfo(null);
+ }
+ catch(Exception e)
+ {
+ System.out.println("Exception Hit");
+ }
+ }
+
+ public void testGetPlatformInfo_N01()
+ {
+ try
+ {
+ SimulatorManager.getPlatformInfo(null);
+ }
+ catch (Exception e)
+ {
+ System.out.println("Exception Hit");
+ }
+ }
}
assertTrue(result);
}
+ public void testAddAttributeString_N02() {
+ String val = null;
+
+ boolean result = false;
+ try {
+
+ simulatorResourceModel.addAttributeString(KEY, val);
+
+ result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val);
+
+ } catch(Exception e) {
+ result = true;
+ }
+
+ assertTrue(result);
+ }
+
public void testAddAttributeString_N03()
{
String val = "@#$$&^*^(*^&";
{
boolean result = true;
- boolean val = true;
+ boolean val;
try
{
+ val=Boolean.parseBoolean("true");
simulatorResourceModel.addAttributeBoolean(KEY, val);
- result = result && ((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue() + "")));
+ result = result && ((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+"")));
- val = false;
+ val = Boolean.parseBoolean("false");
simulatorResourceModel.addAttributeBoolean(KEY, val);
- result = result && !((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue() + "")));
+ result = result && !((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+"")));
}
catch (Exception e)
{
result = result && (simulatorResourceModel.size() == 1);
simulatorResourceModel.addAttributeString("test2", "asdf");
- simulatorResourceModel.addAttributeBoolean("test3", true);
+ simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true"));
simulatorResourceModel.addAttributeDouble("test4", 22.435234);
result = result && (simulatorResourceModel.size() == 4);
{
simulatorResourceModel.addAttributeInt("test1", 1234);
simulatorResourceModel.addAttributeString("test2", "asdf");
- simulatorResourceModel.addAttributeBoolean("test3", true);
+ simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true"));
simulatorResourceModel.addAttributeDouble("test4", 22.435234);
Map<String, ResourceAttribute> attributes = simulatorResourceModel.getAttributes();
result = result && (((Integer)attributes.get("test1").getValue()) == 1234) &&
(((String)attributes.get("test2").getValue()).equals("asdf")) &&
- ((Boolean.parseBoolean(attributes.get("test3").getValue() + "")==true)) &&
+ ((Boolean.parseBoolean(attributes.get("test3").getValue().toString() + "")==true)) &&
(((Double)attributes.get("test4").getValue()) == 22.435234);
}
catch(Exception e)
dlog_print(DLOG_INFO, LOG_TAG, "#### calling findCandidateResources ENTRY!!!!");
std::vector<string> resourceTypes;
resourceTypes.push_back("oic.wk.con");
-
- if (NULL != g_groupManager)
- {
- g_groupManager->findCandidateResources(resourceTypes, &onFoundCandidateResource,
- FINDRESOURCE_TIMEOUT);
- }
-
- resourceTypes.clear();
resourceTypes.push_back("oic.wk.mnt");
- if (NULL != g_groupManager)
- {
- g_groupManager->findCandidateResources(resourceTypes, &onFoundCandidateResource,
- FINDRESOURCE_TIMEOUT);
- }
-
- resourceTypes.clear();
resourceTypes.push_back("factoryset");
+
if (NULL != g_groupManager)
{
g_groupManager->findCandidateResources(resourceTypes, &onFoundCandidateResource,
return;
}
+ if (NULL == g_configurationResource)
+ {
+ dlog_print(DLOG_INFO, LOG_TAG, "Configuration Resource not found.");
+ string logMessage = "FIRST FIND CONFIGURATION RESOURCE <br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+ return;
+ }
+
ConfigurationName name = "all";
std::vector< ConfigurationName > configurations;
configurations.push_back(name);
dlog_print(DLOG_INFO, LOG_TAG, "#### getConfiguration EXIT!!!!");
}
-// Updates the configuration i.e. region value to INDIA
-static void updateConfiguration(std::string newRegionValue)
+// Updates the configuration i.e. Device name to OIC Device
+static void updateConfiguration(std::string newDeviceName)
{
dlog_print(DLOG_INFO, LOG_TAG, "#### updateConfiguration ENTRY!!!!");
- dlog_print(DLOG_INFO, LOG_TAG, "#### %s", newRegionValue.c_str());
+ dlog_print(DLOG_INFO, LOG_TAG, "#### %s", newDeviceName.c_str());
if (NULL == g_configurationCollection || NULL == g_configurationCollection.get())
{
return;
}
+ if (NULL == g_configurationResource)
+ {
+ dlog_print(DLOG_INFO, LOG_TAG, "Configuration Resource not found.");
+ string logMessage = "FIRST FIND CONFIGURATION RESOURCE <br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+ return;
+ }
+
OCStackResult result;
- ConfigurationName name = DEFAULT_REGION;
- ConfigurationValue value = newRegionValue;
+ ConfigurationName name = DEFAULT_DEVICENAME;
+ ConfigurationValue value = newDeviceName;
std::map< ConfigurationName, ConfigurationValue > configurations;
configurations.insert(std::make_pair(name, value));
return;
}
+ if (NULL == g_maintenanceResource)
+ {
+ dlog_print(DLOG_INFO, LOG_TAG, "Maintenance Resource not found.");
+ string logMessage = "FIRST FIND MAINTENANCE RESOURCE <br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+ return;
+ }
+
OCStackResult result;
try
return;
}
+ if (NULL == g_maintenanceResource)
+ {
+ dlog_print(DLOG_INFO, LOG_TAG, "Maintenance Resource not found.");
+ string logMessage = "FIRST FIND MAINTENANCE RESOURCE <br>";
+ dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+ return;
+ }
+
OCStackResult result;
try
}
static void
-list_update_region_cb(void *data, Evas_Object *obj, void *event_info)
+list_update_devicename_cb(void *data, Evas_Object *obj, void *event_info)
{
if (NULL == g_configurationCollection || NULL == g_configurationCollection.get())
{
elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
eext_object_event_callback_add(popup, EEXT_CALLBACK_BACK, eext_popup_back_cb, NULL);
evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
- elm_object_part_text_set(popup, "title,text", "Enter New Region Value");
+ elm_object_part_text_set(popup, "title,text", "Enter new device name to update");
layout = elm_layout_add(popup);
elm_layout_file_set(layout, ELM_DEMO_EDJ, "popup_region_text");
evas_object_size_hint_weight_set(entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
eext_entry_selection_back_event_allow_set(entry, EINA_TRUE);
- elm_object_part_text_set(entry, "elm.guide", "region value");
+ elm_object_part_text_set(entry, "elm.guide", "e.g. OIC Device");
elm_object_part_content_set(layout, "elm.swallow.content" , entry);
region_popup_fields *popup_fields;
elm_list_item_append(list, "Find All Resources",
NULL, NULL, findAllResources, NULL);
elm_list_item_append(list, "Get a Configuration Resource", NULL, NULL, getConfiguration, NULL);
- elm_list_item_append(list, "Update Attribute (Region)", NULL, NULL,
- list_update_region_cb, nf);
+ elm_list_item_append(list, "Update Attribute (Device Name)", NULL, NULL,
+ list_update_devicename_cb, nf);
elm_list_item_append(list, "Factory Reset", NULL, NULL, factoryReset, NULL);
elm_list_item_append(list, "Reboot", NULL, NULL, reboot, NULL);
elm_list_item_append(list, "Get Supported Configuration Units", NULL, NULL,
std::string host = getHostFromURI(oit->getUri());
- tempResource = OCPlatform::constructResourceObject(host, uri, CT_ADAPTER_IP, true,
- oit->getResourceTypes(), m_if);
+ try
+ {
+ tempResource = OCPlatform::constructResourceObject(host, uri, CT_ADAPTER_IP, true,
+ oit->getResourceTypes(), m_if);
- p_resources.push_back(tempResource);
+ p_resources.push_back(tempResource);
+ } catch (std::exception& e)
+ {
+ std::cout << "Exception: " << e.what() << std::endl;
+ }
}
// Send GET messages to the child resources in turn.
resource_path + '/include' ,
resource_path + '/oc_logger/include',
resource_path + '/csdk/stack/include',
- resource_path + '/csdk/ocrandom/include',
+ resource_path + '/c_common/ocrandom/include',
resource_path + '/csdk/logger/include'
])
echo "Framework: Copying includes..."
cp -r resource/csdk/stack/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/csdk/ocsocket/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/csdk/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
+cp -r resource/c_common/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/csdk/ocmalloc/include/*.h $FRAMEWORK_BUNDLE/Headers
echo "Framework: Creating plist..."
echo "Framework: Copying includes..."
cp -r resource/csdk/stack/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/csdk/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
+cp -r resource/c_common/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/csdk/ocmalloc/include/*.h $FRAMEWORK_BUNDLE/Headers
echo "Framework: Creating plist..."
cp resource/csdk/stack/include/*.h %{buildroot}%{_includedir}
cp resource/csdk/logger/include/*.h %{buildroot}%{_includedir}
-cp resource/csdk/ocrandom/include/*.h %{buildroot}%{_includedir}
+cp resource/c_common/ocrandom/include/*.h %{buildroot}%{_includedir}
cp -r resource/oc_logger/include/* %{buildroot}%{_includedir}
cp resource/include/*.h %{buildroot}%{_includedir}