RESET/ACK messages requirement to add additional data from CA .
authorAshok Channa <ashok.channa@samsung.com>
Thu, 29 Jan 2015 06:07:25 +0000 (15:07 +0900)
committerSudarshan Prasad <sudarshan.prasad@intel.com>
Tue, 3 Feb 2015 19:23:33 +0000 (19:23 +0000)
 1) CA layer provide new CAResponseResult_t element to represent empty message.
2) RI can use 'SendResponse' for RESET and ACK(separated response)
with CAResponseResult and CA_Info_t->CAMessageType_t
 3) CA layer will add token information according to the message id of empty message. and
        ( The message id should be from CON type message. )

Signed-off-by: Ashok Channa <ashok.channa@samsung.com>
Change-Id: Ib926601cf9eb1693a0faedf9834d67f9ba0ccd50
Reviewed-on: https://gerrit.iotivity.org/gerrit/268
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Sudarshan Prasad <sudarshan.prasad@intel.com>
18 files changed:
resource/csdk/connectivity/api/cacommon.h
resource/csdk/connectivity/inc/caprotocolmessage.h
resource/csdk/connectivity/inc/caprotocolmessage_singlethread.h
resource/csdk/connectivity/inc/caretransmission.h
resource/csdk/connectivity/inc/caretransmission_singlethread.h
resource/csdk/connectivity/samples/android/sample_service/jni/ResourceModel.c
resource/csdk/connectivity/samples/android/sample_service/jni/com_iotivity_service_RMInterface.h
resource/csdk/connectivity/samples/android/sample_service/src/com/iotivity/service/MainActivity.java
resource/csdk/connectivity/samples/android/sample_service/src/com/iotivity/service/RMInterface.java
resource/csdk/connectivity/samples/arduino/casample.cpp
resource/csdk/connectivity/samples/linux/sample_main.c
resource/csdk/connectivity/samples/tizen/casample.c
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/camessagehandler_singlethread.c
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/caprotocolmessage_singlethread.c
resource/csdk/connectivity/src/caretransmission.c
resource/csdk/connectivity/src/caretransmission_singlethread.cpp

index e40d199..796a72f 100644 (file)
@@ -245,10 +245,11 @@ typedef enum
     CA_SUCCESS = 200,           /**< Success */
     CA_CREATED = 201,           /**< Created */
     CA_DELETED = 202,           /**< Deleted */
+    CA_EMPTY = 231,             /**< Empty */
     CA_BAD_REQ = 400,           /**< Bad Request */
     CA_BAD_OPT = 402,           /**< Bad Option */
     CA_NOT_FOUND = 404,         /**< Not found */
-    CA_RETRANSMIT_TIMEOUT = 500 /**< Retransmit timeout */
+    CA_RETRANSMIT_TIMEOUT = 531 /**< Retransmit timeout */
     /* Response status code - END HERE */
 } CAResponseResult_t;
 
index b457410..ee91e27 100644 (file)
@@ -74,18 +74,26 @@ uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outRe
  * @brief   creates pdu from the request information
  * @param   code         [IN]    request or response code
  * @param   options      [IN]    options for the request and response
- * @param   outUri       [IN]    information to create pdu
+ * @param   info         [IN]    pdu information such as request code ,response code
  * @return  coap_pdu_t
  */
 coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,
                                   const CAInfo_t info);
 
 /**
+ * @brief   creates pdu for ACK or RESET type
+ * @param   code         [IN]    request or response code
+ * @param   info         [IN]    pdu information such as response code
+ * @return  coap_pdu_t
+ */
+coap_pdu_t *CACreatePDUforRSTandACK(const code_t code, const CAInfo_t info);
+
+/**
  * @brief   creates pdu from the request information and paylod
  * @param   code         [IN]    request or response code alloted
  * @param   options      [IN]    options for the request and response backpacked
  * @param   payload      [IN]    payload for the request or response consumed
- * @param   outUri       [IN]    information to create pdu
+ * @param   info         [IN]    pdu information such as request code ,response code
  * @return  coap_pdu_t
  */
 
@@ -167,6 +175,14 @@ void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *out
 coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode);
 
 /**
+ * @brief   get Token fromn received data(pdu)
+ * @param   pdu          [IN]  received pdu
+ * @param   outCode      [IN]  Token received
+ * @return  None
+ */
+CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo);
+
+/**
  * @brief  generates the token
  * @param   token        [OUT]   generated token
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
@@ -204,6 +220,14 @@ CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size
  */
 uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size);
 
+/**
+ * @brief   gets code PDU binary data
+ * @param   pdu        [IN]    pdu data
+ * @param   size       [IN]    size of pdu data
+ * @return  code
+ */
+CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index 582825b..042131d 100644 (file)
@@ -84,6 +84,14 @@ coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,
                                   const CAInfo_t info);
 
 /**
+ * @brief   creates pdu for ACK or RESET type
+ * @param   code         [IN]    request or response code
+ * @param   info         [IN]    pdu information such as response code
+ * @return  coap_pdu_t
+ */
+coap_pdu_t *CACreatePDUforRSTandACK(const code_t code, const CAInfo_t info);
+
+/**
  * @brief   creates pdu from the request information and paylod
  * @param   code         [IN]    request or response code alloted
  * @param   options      [IN]    options for the request and response backpacked
@@ -170,6 +178,14 @@ void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *out
 coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode);
 
 /**
+ * @brief   get Token fromn received data(pdu)
+ * @param   pdu          [IN]  received pdu
+ * @param   outCode      [IN]  Token received
+ * @return  None
+ */
+CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo);
+
+/**
  * @brief  generates the token
  * @param   token        [OUT]   generated token
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
@@ -207,6 +223,14 @@ CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size
  */
 uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size);
 
+/**
+ * @brief   gets code PDU binary data
+ * @param   pdu        [IN]    pdu data
+ * @param   size       [IN]    size of pdu data
+ * @return  code
+ */
+CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index 2568acc..43d1bb7 100644 (file)
@@ -123,10 +123,12 @@ CAResult_t CARetransmissionSentData(CARetransmission_t* context,
  * @param   endpoint    [IN]endpoint information
  * @param   pdu         [IN]received pdu binary data
  * @param   size        [IN]received pdu binary data size
+ * @param   void        [OUT] pdu data of the request for reset and ack
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
-                                        const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size);
+                                        const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                        uint32_t size, void **retransmissionPdu);
 
 /**
  * @brief   Stopping the retransmission context
index 0502e2d..bcfe0d1 100644 (file)
@@ -108,10 +108,12 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context,
  * @param   endpoint    [IN]    endpoint information
  * @param   pdu         [IN]    received pdu binary data
  * @param   size        [IN]    received pdu binary data size
+ * @param   void        [OUT]   pdu data of the request for reset and ack
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
-                                        const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size);
+                                        const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                        uint32_t size, void **retransmissionPdu);
 
 /**
  * @brief   Stopping the retransmission context
index 9736b8d..e6707e2 100644 (file)
@@ -33,7 +33,7 @@ void send_response(const CARemoteEndpoint_t* endpoint, CAToken_t request_token);
 void get_resource_uri(char *URI, char *resourceURI, int length);
 int get_secure_information(CAPayload_t payLoad);
 CAResult_t get_network_type(int selectedNetwork);
-void callback(char *subject, char *receicedData);
+void callback(char *subject, char *receivedData);
 
 CAConnectivityType_t gSelectedNwType;
 static CAToken_t gLastRequestToken = NULL;
@@ -45,6 +45,9 @@ static const char *gNormalInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\"
 static jobject gResponseListenerObject = NULL;
 extern JavaVM *g_jvm;
 
+static CARemoteEndpoint_t* clientEndpoint =NULL;
+static CAToken_t clientToken;
+
 // init
 JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj, jobject listener){
     LOGI("setNativeResponseListener");
@@ -100,15 +103,42 @@ int32_t SetCredentials()
 }
 #endif
 
+JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
+{
+    printf("JNI_OnLoad");
+
+    JNIEnv* env;
+    if((*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6) != JNI_OK)
+    {
+        return -1;
+    }
+    g_jvm = jvm;  /* cache the JavaVM pointer */
+
+    CANativeJNISetJavaVM(g_jvm);
+
+    return JNI_VERSION_1_6;
+}
+
+void JNI_OnUnload(JavaVM *jvm, void *reserved)
+{
+    printf("JNI_OnUnload");
+
+    JNIEnv* env;
+    if((*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6) != JNI_OK)
+    {
+        return;
+    }
+    g_jvm = 0;
+    return;
+}
+
 JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMInitialize
   (JNIEnv *env, jobject obj, jobject context)
 {
     LOGI("RMInitialize");
-    //Currently set context for WiFiCore
-    CAJniSetContext(context);
-    CALEServerJNISetContext(env, context);
-    CALEClientJNISetContext(env, context);
-    CALENetworkMonitorJNISetContext(env, context);
+
+    //Currently set context for Android Platform
+    CANativeJNISetContext(env, context);
 
     CAResult_t res;
 
@@ -281,13 +311,10 @@ JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendRequest(JNIEn
 }
 
 JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendResponse(JNIEnv *env,
-    jobject obj, jstring uri, jstring payload, jint selectedNetwork, jint isSecured)
+    jobject obj, jint selectedNetwork, jint isSecured, jint msgType, jint responseValue)
 {
     LOGI("RMSendResponse");
 
-    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
-    LOGI("RMSendResponse - %s", strUri);
-
     CAResult_t res;
 
     LOGI("selectedNetwork - %d", selectedNetwork);
@@ -299,74 +326,54 @@ JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendResponse(JNIE
         return;
     }
 
-    //create remote endpoint
-    CARemoteEndpoint_t* endpoint = NULL;
-
-    if(CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t)strUri, gSelectedNwType, &endpoint))
+    if (clientEndpoint == NULL)
     {
-        LOGI("Could not create remote end point");
-        CADestroyRemoteEndpoint(endpoint);
+        LOGI("No Request received");
         return;
     }
 
-    CAMessageType_t messageType = CA_MSG_ACKNOWLEDGE;
-
-    // create token
-    CAToken_t token = NULL;
-    res = CAGenerateToken(&token);
-    if (res != CA_STATUS_OK)
-    {
-        LOGI("token generate error!");
-        token = NULL;
-    }
-
-    char resourceURI[15] = {0};
-
-    get_resource_uri((const CAURI_t)strUri, resourceURI, 14);
+    CAMessageType_t messageType = msgType;
 
     CAInfo_t responseData;
     memset(&responseData, 0, sizeof(CAInfo_t));
-    responseData.token = token;
+    responseData.token = clientToken;
 
-    const char* strPayload = (*env)->GetStringUTFChars(env, payload, NULL);
     if (isSecured == 1)
     {
-        int length = strlen(gSecureInfoData) + strlen(resourceURI) + 1;
+        int length = strlen(gSecureInfoData) + strlen(clientEndpoint->resourceUri) + 1;
         responseData.payload = (CAPayload_t) malloc(length);
-        sprintf(responseData.payload, gSecureInfoData, resourceURI, gLocalSecurePort);
+        sprintf(responseData.payload, gSecureInfoData, clientEndpoint->resourceUri, gLocalSecurePort);
     }
     else
     {
-        int length = strlen(strPayload) + strlen(resourceURI) + 1;
+        int length = strlen("sendResponse Payload") + strlen(clientEndpoint->resourceUri) + 1;
         responseData.payload = (CAPayload_t) malloc(length);
-        sprintf(responseData.payload, strPayload, resourceURI);
+        sprintf(responseData.payload, gNormalInfoData, clientEndpoint->resourceUri);
     }
 
     responseData.type = messageType;
 
     CAResponseInfo_t responseInfo;
     memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
-    responseInfo.result = CA_SUCCESS;
+    responseInfo.result = responseValue;
     responseInfo.info = responseData;
 
     // send request
-    if(CA_STATUS_OK != CASendResponse(endpoint, &responseInfo))
+    if(CA_STATUS_OK != CASendResponse(clientEndpoint, &responseInfo))
     {
         LOGI("Could not send response");
     }
 
-    LOGI("Send response");
-
     // destroy token
-    if (token != NULL)
+    if (clientToken != NULL)
     {
-        CADestroyToken(token);
+        CADestroyToken(clientToken);
     }
 
     // destroy remote endpoint
-    if (endpoint != NULL)
+    if (clientEndpoint != NULL)
     {
-        CADestroyRemoteEndpoint(endpoint);
+        CADestroyRemoteEndpoint(clientEndpoint);
     }
 
 }
@@ -525,6 +532,13 @@ JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMHandleRequestResp
 
 void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo)
 {
+
+    char *cloneUri = NULL;
+    char *cloneRemoteAddress = NULL;
+    char *clonePayload = NULL;
+    char *cloneOptionData = NULL;
+    uint32_t len = 0;
+
     if (!object)
     {
         LOGI("Remote endpoint is NULL!");
@@ -540,19 +554,64 @@ void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* re
     LOGI("##########received request from remote device #############\n");
     LOGI("Uri: %s\n", object->resourceUri);
     LOGI("Remote Address: %s\n", object->addressInfo.IP.ipAddress);
-
     LOGI("Data: %s\n", requestInfo->info.payload);
+    LOGI("Token: %s\n", requestInfo->info.token);
+    LOGI("Code: %d\n", requestInfo->method);
 
     if (NULL != gResponseListenerObject)
     {
         callback("received request from remote device", "#######");
-        callback("Uri: ", object->resourceUri);
 
-        callback("Remote Address: ", (char *) object->addressInfo.IP.ipAddress);
+        if (object->resourceUri != NULL)
+        {
+            len = strlen(object->resourceUri);
+            cloneUri = (char *) OICMalloc(sizeof(char) * (len + 1));
+
+            if (cloneUri == NULL)
+            {
+                LOGI("CACloneRemoteEndpoint Out of memory");
+                return;
+            }
+
+            memset(cloneUri, 0, sizeof(char) * (len + 1));
+            strncpy(cloneUri, object->resourceUri, len);
+
+            callback("Uri: ", cloneUri);
+            free(cloneUri);
+        }
+
+        len = strlen(object->addressInfo.IP.ipAddress);
+        cloneRemoteAddress = (char *) OICMalloc(sizeof(char) * (len + 1));
 
-        if(requestInfo->info.payload)
+        if (cloneRemoteAddress == NULL)
         {
-            callback("Data: ", requestInfo->info.payload);
+            LOGI("CACloneRemoteEndpoint Out of memory");
+            return;
+        }
+
+        memset(cloneRemoteAddress, 0, sizeof(char) * (len + 1));
+        strncpy(cloneRemoteAddress, object->addressInfo.IP.ipAddress, len);
+
+        callback("Remote Address: ", cloneRemoteAddress);
+        free(cloneRemoteAddress);
+
+
+        if(requestInfo->info.payload != NULL)
+        {
+            len = strlen(requestInfo->info.payload);
+            clonePayload = (char *) OICMalloc(sizeof(char) * (len + 1));
+
+            if (clonePayload == NULL)
+            {
+                LOGI("CACloneRemoteEndpoint Out of memory");
+                return;
+            }
+
+            memset(clonePayload, 0, sizeof(char) * (len + 1));
+            strncpy(clonePayload, requestInfo->info.payload, len);
+
+            callback("Data: ", clonePayload);
+            free(clonePayload);
         }
     }
 
@@ -567,6 +626,9 @@ void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* re
     {
         uint32_t len = requestInfo->info.numOptions;
         uint32_t i;
+
+        LOGI("Option count: %d\n", requestInfo->info.numOptions);
+
         for (i = 0; i < len; i++)
         {
             LOGI("Option %d\n", i + 1);
@@ -576,22 +638,37 @@ void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* re
 
             if (NULL != gResponseListenerObject)
             {
-                char tmpbuf[30];
-                sprintf(tmpbuf, "%d", i + 1);
-                callback("Option: ", tmpbuf);
+                char optionInfo[1024] = {0,};
+                sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i+1,
+                        requestInfo->info.options[i].optionID, requestInfo->info.options[i].optionLength);
+
+                callback("Option info: ", optionInfo);
 
-                sprintf(tmpbuf, "%d", requestInfo->info.options[i].optionID);
-                callback("ID: ", tmpbuf);
+                if (requestInfo->info.options[i].optionData != NULL)
+                {
+                    uint32_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
+                    cloneOptionData = (char *) OICMalloc(sizeof(char) * (optionDataLen + 1));
 
-                sprintf(tmpbuf, "Data:[%d]",  requestInfo->info.options[i].optionLength);
-                callback("tmpbuf: ", requestInfo->info.options[i].optionData);
+                    if (cloneOptionData == NULL)
+                    {
+                        LOGI("CACloneRemoteEndpoint Out of memory");
+                        return;
+                    }
+
+                    memset(cloneOptionData, 0, sizeof(char) * (optionDataLen + 1));
+                    strncpy(cloneOptionData, requestInfo->info.options[i].optionData, optionDataLen);
+
+                    callback("Option Data: ", cloneOptionData);
+                    free(cloneOptionData);
+                }
             }
         }
     }
+
     printf("############################################################\n");
 
     //Check if this has secure communication information
-    if (requestInfo->info.payload)
+    if (requestInfo->info.payload && object->resourceUri)
     {
         int securePort = get_secure_information(requestInfo->info.payload);
         if (0 < securePort) //Set the remote endpoint secure details and send response
@@ -626,30 +703,79 @@ void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* re
 
     gReceived = 1;
 
-    // response
-//    send_response(object, (requestInfo != NULL) ? requestInfo->info.token : "");
-
+    clientEndpoint = object;
+    clientToken = requestInfo->info.token;
 }
 
 void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo)
 {
 
+    char *cloneUri = NULL;
+    char *cloneRemoteAddress = NULL;
+    char *clonePayload = NULL;
+    char *cloneOptionData = NULL;
+    uint32_t len = 0;
+
     LOGI("##########Received response from remote device #############\n");
     LOGI("Uri: %s\n", object->resourceUri);
     LOGI("Remote Address: %s\n", object->addressInfo.IP.ipAddress);
     LOGI("response result: %d\n", responseInfo->result);
     LOGI("Data: %s\n", responseInfo->info.payload);
+    LOGI("Token: %s\n", responseInfo->info.token);
+    LOGI("Code: %d\n", responseInfo->result);
 
     if (NULL != gResponseListenerObject)
     {
-        callback("received response from remote device", "#######");
-        callback("Uri: ", object->resourceUri);
+        if (object->resourceUri != NULL)
+        {
+            len = strlen(object->resourceUri);
+            cloneUri = (char *) OICMalloc(sizeof(char) * (len + 1));
 
-        callback("Remote Address: ", (char *)object->addressInfo.IP.ipAddress);
+            if (cloneUri == NULL)
+            {
+                LOGI("CACloneRemoteEndpoint Out of memory");
+                return;
+            }
+
+            memset(cloneUri, 0, sizeof(char) * (len + 1));
+            strncpy(cloneUri, object->resourceUri, len);
 
-        if(responseInfo->info.payload)
+            callback("Uri: ", cloneUri);
+            free(cloneUri);
+        }
+
+        len = strlen(object->addressInfo.IP.ipAddress);
+        cloneRemoteAddress = (char *) OICMalloc(sizeof(char) * (len + 1));
+
+        if (cloneRemoteAddress == NULL)
         {
-            callback("Data: ", responseInfo->info.payload);
+            LOGI("CACloneRemoteEndpoint Out of memory");
+            return;
+        }
+
+        memset(cloneRemoteAddress, 0, sizeof(char) * (len + 1));
+        strncpy(cloneRemoteAddress, object->addressInfo.IP.ipAddress, len);
+
+        callback("Remote Address: ", cloneRemoteAddress);
+        free(cloneRemoteAddress);
+
+
+        if(responseInfo->info.payload != NULL)
+        {
+            len = strlen(responseInfo->info.payload);
+            clonePayload = (char *) OICMalloc(sizeof(char) * (len + 1));
+
+            if (clonePayload == NULL)
+            {
+                LOGI("CACloneRemoteEndpoint Out of memory");
+                return;
+            }
+
+            memset(clonePayload, 0, sizeof(char) * (len + 1));
+            strncpy(clonePayload, responseInfo->info.payload, len);
+
+            callback("Data: ", clonePayload);
+            free(clonePayload);
         }
     }
 
@@ -666,15 +792,28 @@ void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t*
 
             if (NULL != gResponseListenerObject)
             {
-                char tmpbuf[30];
-                sprintf(tmpbuf, "%d", i + 1);
-                callback("Option: ", tmpbuf);
-
-                sprintf(tmpbuf, "%d", responseInfo->info.options[i].optionID);
-                callback("ID: ", tmpbuf);
-
-                sprintf(tmpbuf, "Data:[%d]",  responseInfo->info.options[i].optionLength);
-                callback("tmpbuf: ", responseInfo->info.options[i].optionData);
+                char optionInfo[1024] = {0,};
+                sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i+1,
+                        responseInfo->info.options[i].optionID,
+                        responseInfo->info.options[i].optionLength);
+
+                callback("Option info: ", optionInfo);
+
+                if (responseInfo->info.options[i].optionData != NULL)
+                {
+                    uint32_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
+                    cloneOptionData = (char *) OICMalloc(sizeof(char) * (optionDataLen + 1));
+
+                    if (cloneOptionData == NULL)
+                    {
+                        LOGI("CACloneRemoteEndpoint Out of memory");
+                        return;
+                    }
+                    memset(cloneOptionData, 0, sizeof(char) * (optionDataLen + 1));
+                    strncpy(cloneOptionData, responseInfo->info.options[i].optionData, optionDataLen);
+                    callback("Option Data: ", cloneOptionData);
+                    free(cloneOptionData);
+                }
             }
         }
     }
@@ -692,24 +831,6 @@ void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t*
     }
 }
 
-void send_response(const CARemoteEndpoint_t* endpoint, CAToken_t request_token)
-{
-    LOGI("send_response");
-
-    CAInfo_t responseData;
-    memset(&responseData, 0, sizeof(CAInfo_t));
-    responseData.token = request_token;
-    responseData.payload = "response payload";
-
-    CAResponseInfo_t responseInfo;
-    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
-    responseInfo.result = 203;
-    responseInfo.info = responseData;
-
-    // send request
-    CASendResponse(endpoint, &responseInfo);
-}
-
 void get_resource_uri(char *URI, char *resourceURI, int length)
 {
     char *startPos = URI;
@@ -814,7 +935,7 @@ CAResult_t get_network_type(int selectedNetwork)
     return CA_NOT_SUPPORTED;
 }
 
-void callback(char *subject, char *receicedData)
+void callback(char *subject, char *receivedData)
 {
     JNIEnv* env = NULL;
     int status = (*g_jvm)->GetEnv(g_jvm, (void **) &env, JNI_VERSION_1_6);
@@ -824,6 +945,7 @@ void callback(char *subject, char *receicedData)
     jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived", "(Ljava/lang/String;Ljava/lang/String;)V");
 
     jstring jsubject = (*env)->NewStringUTF(env, (char*)subject);
-    jstring jreceivedData = (*env)->NewStringUTF(env, (char*)receicedData);
+    jstring jreceivedData = (*env)->NewStringUTF(env, (char*)receivedData);
     (*env)->CallVoidMethod(env, gResponseListenerObject, mid, jsubject, jreceivedData);
+
 }
index 47fb06b..6f6717a 100644 (file)
@@ -69,10 +69,10 @@ JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendRequest
 /*
  * Class:     com_iotivity_service_RMInterface
  * Method:    RMSendResponse
- * Signature: (Ljava/lang/String;III)V
+ * Signature: (IIII)V
  */
 JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendResponse
-  (JNIEnv *, jobject, jstring, jstring, jint, jint);
+  (JNIEnv *, jobject, jint, jint, jint, jint);
 
 /*
  * Class:     com_iotivity_service_RMInterface
index 5a4f1f2..0515897 100644 (file)
@@ -20,544 +20,624 @@ import com.iotivity.sample_service.R;
 
 public class MainActivity extends Activity {
 
-       static RMInterface RM = new RMInterface();
+    static RMInterface RM = new RMInterface();
 
-       private final static String TAG = "MainActivity";
+    private final static String TAG = "MainActivity";
 
-       private final CharSequence[] mCheckBoxItems = { Network.WIFI.name(),
-                       Network.EDR.name(), Network.LE.name() };
+    private final CharSequence[] mCheckBoxItems = { Network.WIFI.name(),
+            Network.EDR.name(), Network.LE.name() };
 
-       private final CharSequence[] mDTLSCheckBoxItems = { DTLS.SECURED.name(),
-                       DTLS.UNSECURED.name() };
+    private final CharSequence[] mDTLSCheckBoxItems = { DTLS.UNSECURED.name(),
+            DTLS.SECURED.name() };
 
-       private final CharSequence[] mMsgTyleCheckBoxItems = { MsgType.CON.name(),
-                       MsgType.NON.name() };
+    private final CharSequence[] mMsgTyleCheckBoxItems = { MsgType.CON.name(),
+            MsgType.NON.name(), MsgType.ACK.name(), MsgType.RESET.name() };
 
-       private enum Mode {
-               SERVER, CLIENT, BOTH, UNKNOWN
-       };
+    private final CharSequence[] mResponseResultCheckBoxItems = {
+            ResponseResult.CA_SUCCESS.name(), ResponseResult.CA_CREATED.name(),
+            ResponseResult.CA_DELETED.name(), ResponseResult.CA_EMPTY.name(),
+            ResponseResult.CA_BAD_REQ.name(), ResponseResult.CA_BAD_OPT.name(),
+            ResponseResult.CA_NOT_FOUND.name(),
+            ResponseResult.CA_RETRANSMIT_TIMEOUT.name() };
 
-       private enum Network {
-               WIFI, EDR, LE
-       };
+    private enum Mode {
+        SERVER, CLIENT, BOTH, UNKNOWN
+    };
 
-       private enum DTLS {
-               SECURED, UNSECURED
-       };
+    private enum Network {
+        WIFI, EDR, LE
+    };
 
-       private enum MsgType {
-               CON, NON
-       };
+    private enum DTLS {
+        UNSECURED, SECURED
+    };
 
-       private Mode mCurrentMode = Mode.UNKNOWN;
+    private enum MsgType {
+        CON, NON, ACK, RESET
+    };
 
-       private ArrayList<Integer> mSelectedItems = new ArrayList<Integer>();
+    private enum ResponseResult {
+        CA_SUCCESS, CA_CREATED, CA_DELETED, CA_EMPTY, CA_BAD_REQ, CA_BAD_OPT,
+        CA_NOT_FOUND, CA_RETRANSMIT_TIMEOUT
+    }
 
-       private RelativeLayout mFindResourceLayout = null;
+    private Mode mCurrentMode = Mode.UNKNOWN;
 
-       private RelativeLayout mSendNotificationLayout = null;
+    private ArrayList<Integer> mSelectedItems = new ArrayList<Integer>();
 
-       private RelativeLayout mSendRequestLayout = null;
+    private RelativeLayout mFindResourceLayout = null;
 
-       private RelativeLayout mSendRequestSettingLayout = null;
+    private RelativeLayout mSendNotificationLayout = null;
 
-       private RelativeLayout mSendResponseNotiSettingLayout = null;
+    private RelativeLayout mSendRequestLayout = null;
 
-       private RelativeLayout mReceiveLayout = null;
+    private RelativeLayout mSendRequestSettingLayout = null;
 
-       private RelativeLayout mFindTitleLayout = null;
+    private RelativeLayout mSendResponseNotiSettingLayout = null;
 
-       private RelativeLayout mRequestTitleLayout = null;
+    private RelativeLayout mReceiveLayout = null;
 
-       private RelativeLayout mResponseNotificationTitleLayout = null;
+    private RelativeLayout mFindTitleLayout = null;
 
-       private RelativeLayout mAdvertiseTitleLayout = null;
+    private RelativeLayout mRequestTitleLayout = null;
 
-       private RelativeLayout mHandleTitleLayout = null;
+    private RelativeLayout mResponseNotificationTitleLayout = null;
 
-       private RelativeLayout mPayLoadClientEditLayout = null;
+    private RelativeLayout mAdvertiseTitleLayout = null;
 
-       private RelativeLayout mPayLoadServerEditLayout = null;
+    private RelativeLayout mHandleTitleLayout = null;
 
-       private RelativeLayout mAdvertiseResourceLayout = null;
+    private RelativeLayout mPayLoadClientEditLayout = null;
 
-       private RelativeLayout mServerButtonLayout = null;
+    private RelativeLayout mPayLoadServerEditLayout = null;
 
-       private TextView mMode_tv = null;
+    private RelativeLayout mAdvertiseResourceLayout = null;
 
-       private TextView mNetwork_tv = null;
+    private RelativeLayout mServerButtonLayout = null;
 
-       private EditText mUri_ed = null;
+    private TextView mMode_tv = null;
 
-       private EditText mNotification_ed = null;
+    private TextView mNetwork_tv = null;
 
-       private EditText mReqData_ed = null;
+    private EditText mUri_ed = null;
 
-       private EditText mPayload_ed = null;
+    private EditText mNotification_ed = null;
 
-       private Button mFind_btn = null;
+    private EditText mReqData_ed = null;
 
-       private Button mNotify_btn = null;
+    private EditText mPayload_ed = null;
 
-       private Button mAdvertiseResource_btn = null;
+    private EditText mAdvertise_ed = null;
 
-       private Button mReqeust_btn = null;
+    private Button mFind_btn = null;
 
-       private Button mReqeust_setting_btn = null;
+    private Button mNotify_btn = null;
 
-       private Button mResponse_Notify_setting_btn = null;
+    private Button mAdvertiseResource_btn = null;
 
-       private Button mResponse_btn = null;
+    private Button mReqeust_btn = null;
 
-       private Button mRecv_btn = null;
+    private Button mReqeust_setting_btn = null;
 
-       private Handler mLogHandler = null;
+    private Button mResponse_Notify_setting_btn = null;
 
-       /**
-        * Defined ConnectivityType in cacommon.c
-        * 
-        * CA_ETHERNET = (1 << 0) CA_WIFI = (1 << 1) CA_EDR = (1 << 2) CA_LE = (1 <<
-        * 3)
-        */
-       private int CA_WIFI = (1 << 1);
-       private int CA_EDR = (1 << 2);
-       private int CA_LE = (1 << 3);
-       private int isSecured = 0;
-       private int msgType = 0;
-       private int selectedItem = 0;
-       int selectedNetwork = 0;
+    private Button mResponse_btn = null;
 
-       @Override
-       protected void onCreate(Bundle savedInstanceState) {
-               super.onCreate(savedInstanceState);
-               setContentView(R.layout.activity_main);
+    private Button mRecv_btn = null;
 
-               RM.setResponseListener(this);
+    private Handler mLogHandler = null;
 
-               mLogHandler = new Handler();
-               TextView logView = (TextView) findViewById(R.id.tv_result);
-               DLog.setTextView(mLogHandler, logView);
+    /**
+     * Defined ConnectivityType in cacommon.c
+     * 
+     * CA_ETHERNET = (1 << 0) CA_WIFI = (1 << 1) CA_EDR = (1 << 2) CA_LE = (1 <<
+     * 3)
+     */
+    private int CA_WIFI = (1 << 1);
+    private int CA_EDR = (1 << 2);
+    private int CA_LE = (1 << 3);
+    private int isSecured = -1;
+    private int msgType = -1;
+    private int responseValue = -1;
+    private int selectedItem = 0;
+    private int selectedResponseValue = -1;
+    int selectedNetwork = 0;
 
-               // Initialize UI
-               // common
-               mReceiveLayout = (RelativeLayout) findViewById(R.id.layout_receive);
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
 
-               // client
-               mSendRequestLayout = (RelativeLayout) findViewById(R.id.layout_request);
-               mSendRequestSettingLayout = (RelativeLayout) findViewById(R.id.layout_request_setting_for_client);
-               mFindResourceLayout = (RelativeLayout) findViewById(R.id.layout_find);
-               mFindTitleLayout = (RelativeLayout) findViewById(R.id.layout_find_title);
-               mRequestTitleLayout = (RelativeLayout) findViewById(R.id.layout_request_title);
-               mHandleTitleLayout = (RelativeLayout) findViewById(R.id.layout_handle_title);
-               mPayLoadClientEditLayout = (RelativeLayout) findViewById(R.id.layout_payload_client_ed);
+        RM.setResponseListener(this);
 
-               // server
-               mSendNotificationLayout = (RelativeLayout) findViewById(R.id.layout_notify);
-               mPayLoadServerEditLayout = (RelativeLayout) findViewById(R.id.layout_payload_server_ed);
-               mSendResponseNotiSettingLayout = (RelativeLayout) findViewById(R.id.layout_request_setting_for_server);
-               mServerButtonLayout = (RelativeLayout) findViewById(R.id.layout_server_bt);
-               mResponseNotificationTitleLayout = (RelativeLayout) findViewById(R.id.layout_Response_Noti_title);
-               mAdvertiseTitleLayout = (RelativeLayout) findViewById(R.id.layout_advertise_title);
-               mAdvertiseResourceLayout = (RelativeLayout) findViewById(R.id.layout_advertise_resource);
+        mLogHandler = new Handler();
+        TextView logView = (TextView) findViewById(R.id.tv_result);
+        DLog.setTextView(mLogHandler, logView);
 
-               mMode_tv = (TextView) findViewById(R.id.tv_mode);
-               mNetwork_tv = (TextView) findViewById(R.id.tv_network);
+        // Initialize UI
+        // common
+        mReceiveLayout = (RelativeLayout) findViewById(R.id.layout_receive);
 
-               mUri_ed = (EditText) findViewById(R.id.et_uri);
-               mNotification_ed = (EditText) findViewById(R.id.et_notification);
-               mReqData_ed = (EditText) findViewById(R.id.et_req_data);
-               mPayload_ed = (EditText) findViewById(R.id.et_payload_data_for_server);
+        // client
+        mSendRequestLayout = (RelativeLayout) findViewById(R.id.layout_request);
+        mSendRequestSettingLayout = (RelativeLayout) 
+                findViewById(R.id.layout_request_setting_for_client);
+        mFindResourceLayout = (RelativeLayout) findViewById(R.id.layout_find);
+        mFindTitleLayout = (RelativeLayout) findViewById(R.id.layout_find_title);
+        mRequestTitleLayout = (RelativeLayout) findViewById(R.id.layout_request_title);
+        mHandleTitleLayout = (RelativeLayout) findViewById(R.id.layout_handle_title);
+        mPayLoadClientEditLayout = (RelativeLayout) findViewById(R.id.layout_payload_client_ed);
 
-               mFind_btn = (Button) findViewById(R.id.btn_find_resource);
-               mResponse_btn = (Button) findViewById(R.id.btn_sendresponse);
-               mNotify_btn = (Button) findViewById(R.id.btn_notify);
-               mAdvertiseResource_btn = (Button) findViewById(R.id.btn_advertise);
-               mReqeust_btn = (Button) findViewById(R.id.btn_Request);
-               mReqeust_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_client);
-               mResponse_Notify_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_server);
-               mRecv_btn = (Button) findViewById(R.id.btn_receive);
+        // server
+        mSendNotificationLayout = (RelativeLayout) findViewById(R.id.layout_notify);
+        mPayLoadServerEditLayout = (RelativeLayout) 
+                findViewById(R.id.layout_payload_server_ed);
+        mSendResponseNotiSettingLayout = (RelativeLayout) 
+                findViewById(R.id.layout_request_setting_for_server);
+        mServerButtonLayout = (RelativeLayout) findViewById(R.id.layout_server_bt);
+        mResponseNotificationTitleLayout = (RelativeLayout) 
+                findViewById(R.id.layout_Response_Noti_title);
+        mAdvertiseTitleLayout = (RelativeLayout) findViewById(R.id.layout_advertise_title);
+        mAdvertiseResourceLayout = (RelativeLayout) findViewById(R.id.layout_advertise_resource);
 
-               mFind_btn.setOnClickListener(mFindResourceHandler);
-               mResponse_btn.setOnClickListener(mSendResponseHandler);
-               mNotify_btn.setOnClickListener(mNotifyHandler);
-               mAdvertiseResource_btn.setOnClickListener(mAdvertiseResourceHandler);
-               mReqeust_btn.setOnClickListener(mSendRequestHandler);
-               mReqeust_setting_btn.setOnClickListener(mSendRequestSettingHandler);
-               mResponse_Notify_setting_btn
-                               .setOnClickListener(mSendResponseNotiSettingHandler);
-               mRecv_btn.setOnClickListener(mResponseHandler);
+        mMode_tv = (TextView) findViewById(R.id.tv_mode);
+        mNetwork_tv = (TextView) findViewById(R.id.tv_network);
 
-               showSelectModeView();
-
-               // Initialize Connectivity Abstraction
-               RM.RMInitialize(getApplicationContext());
-               // Select default network(WIFI)
-               RM.RMSelectNetwork(CA_WIFI);
-               // set handler
-               RM.RMRegisterHandler();
-       }
-
-       private void showSelectModeView() {
-
-               mFindResourceLayout.setVisibility(View.INVISIBLE);
-               mSendNotificationLayout.setVisibility(View.INVISIBLE);
-               mSendRequestLayout.setVisibility(View.INVISIBLE);
-               mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
-               mReceiveLayout.setVisibility(View.INVISIBLE);
-               mFindTitleLayout.setVisibility(View.INVISIBLE);
-               mRequestTitleLayout.setVisibility(View.INVISIBLE);
-               mHandleTitleLayout.setVisibility(View.INVISIBLE);
-               mPayLoadClientEditLayout.setVisibility(View.INVISIBLE);
-               mPayLoadServerEditLayout.setVisibility(View.INVISIBLE);
-               mServerButtonLayout.setVisibility(View.INVISIBLE);
-               mResponseNotificationTitleLayout.setVisibility(View.INVISIBLE);
-               mAdvertiseTitleLayout.setVisibility(View.INVISIBLE);
-               mAdvertiseResourceLayout.setVisibility(View.INVISIBLE);
-               mSendResponseNotiSettingLayout.setVisibility(View.INVISIBLE);
-
-               mMode_tv.setText("Select Mode (Server or Client)");
-       }
-
-       private void showNetworkView() {
-
-               mNetwork_tv.setText("Select Network Type");
-       }
-
-       private void showModeView() {
-
-               if (mCurrentMode == Mode.SERVER) {
-
-                       mFindResourceLayout.setVisibility(View.INVISIBLE);
-                       mSendNotificationLayout.setVisibility(View.VISIBLE);
-                       mSendRequestLayout.setVisibility(View.INVISIBLE);
-                       mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
-                       mReceiveLayout.setVisibility(View.VISIBLE);
-
-                       mFindTitleLayout.setVisibility(View.INVISIBLE);
-                       mRequestTitleLayout.setVisibility(View.INVISIBLE);
-                       mHandleTitleLayout.setVisibility(View.VISIBLE);
-                       mPayLoadClientEditLayout.setVisibility(View.INVISIBLE);
-
-                       mPayLoadServerEditLayout.setVisibility(View.VISIBLE);
-                       mServerButtonLayout.setVisibility(View.VISIBLE);
-
-                       mResponseNotificationTitleLayout.setVisibility(View.VISIBLE);
-                       mAdvertiseTitleLayout.setVisibility(View.VISIBLE);
-                       mAdvertiseResourceLayout.setVisibility(View.VISIBLE);
+        mUri_ed = (EditText) findViewById(R.id.et_uri);
+        mNotification_ed = (EditText) findViewById(R.id.et_notification);
+        mReqData_ed = (EditText) findViewById(R.id.et_req_data);
+        mPayload_ed = (EditText) findViewById(R.id.et_payload_data_for_server);
+        mAdvertise_ed = (EditText) findViewById(R.id.et_uri_advertise);
+        mFind_btn = (Button) findViewById(R.id.btn_find_resource);
+        mResponse_btn = (Button) findViewById(R.id.btn_sendresponse);
+        mNotify_btn = (Button) findViewById(R.id.btn_notify);
+        mAdvertiseResource_btn = (Button) findViewById(R.id.btn_advertise);
+        mReqeust_btn = (Button) findViewById(R.id.btn_Request);
+        mReqeust_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_client);
+        mResponse_Notify_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_server);
+        mRecv_btn = (Button) findViewById(R.id.btn_receive);
+
+        mFind_btn.setOnClickListener(mFindResourceHandler);
+        mResponse_btn.setOnClickListener(mSendResponseHandler);
+        mNotify_btn.setOnClickListener(mNotifyHandler);
+        mAdvertiseResource_btn.setOnClickListener(mAdvertiseResourceHandler);
+        mReqeust_btn.setOnClickListener(mSendRequestHandler);
+        mReqeust_setting_btn.setOnClickListener(mSendRequestSettingHandler);
+        mResponse_Notify_setting_btn
+                .setOnClickListener(mSendResponseNotiSettingHandler);
+        mRecv_btn.setOnClickListener(mResponseHandler);
+
+        showSelectModeView();
+
+        // Initialize Connectivity Abstraction
+        RM.RMInitialize(getApplicationContext());
+        // Select default network(WIFI)
+//        RM.RMSelectNetwork(CA_WIFI);
+        // set handler
+        RM.RMRegisterHandler();
+    }
+
+    private void showSelectModeView() {
+
+        mFindResourceLayout.setVisibility(View.INVISIBLE);
+        mSendNotificationLayout.setVisibility(View.INVISIBLE);
+        mSendRequestLayout.setVisibility(View.INVISIBLE);
+        mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
+        mReceiveLayout.setVisibility(View.INVISIBLE);
+        mFindTitleLayout.setVisibility(View.INVISIBLE);
+        mRequestTitleLayout.setVisibility(View.INVISIBLE);
+        mHandleTitleLayout.setVisibility(View.INVISIBLE);
+        mPayLoadClientEditLayout.setVisibility(View.INVISIBLE);
+        mPayLoadServerEditLayout.setVisibility(View.INVISIBLE);
+        mServerButtonLayout.setVisibility(View.INVISIBLE);
+        mResponseNotificationTitleLayout.setVisibility(View.INVISIBLE);
+        mAdvertiseTitleLayout.setVisibility(View.INVISIBLE);
+        mAdvertiseResourceLayout.setVisibility(View.INVISIBLE);
+        mSendResponseNotiSettingLayout.setVisibility(View.INVISIBLE);
+
+        mMode_tv.setText("Select Mode (Server or Client)");
+    }
+
+    private void showNetworkView() {
+
+        mNetwork_tv.setText("Select Network Type");
+    }
+
+    private void showModeView() {
+
+        if (mCurrentMode == Mode.SERVER) {
+
+            mFindResourceLayout.setVisibility(View.INVISIBLE);
+            mSendNotificationLayout.setVisibility(View.VISIBLE);
+            mSendRequestLayout.setVisibility(View.INVISIBLE);
+            mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
+            mReceiveLayout.setVisibility(View.VISIBLE);
+
+            mFindTitleLayout.setVisibility(View.INVISIBLE);
+            mRequestTitleLayout.setVisibility(View.INVISIBLE);
+            mHandleTitleLayout.setVisibility(View.VISIBLE);
+            mPayLoadClientEditLayout.setVisibility(View.INVISIBLE);
+
+            mPayLoadServerEditLayout.setVisibility(View.VISIBLE);
+            mServerButtonLayout.setVisibility(View.VISIBLE);
+
+            mResponseNotificationTitleLayout.setVisibility(View.VISIBLE);
+            mAdvertiseTitleLayout.setVisibility(View.VISIBLE);
+            mAdvertiseResourceLayout.setVisibility(View.VISIBLE);
+
+            mSendResponseNotiSettingLayout.setVisibility(View.VISIBLE);
+
+            mNetwork_tv.setText("");
+
+        } else if (mCurrentMode == Mode.CLIENT) {
 
-                       mSendResponseNotiSettingLayout.setVisibility(View.VISIBLE);
+            mFindResourceLayout.setVisibility(View.VISIBLE);
+            mSendNotificationLayout.setVisibility(View.INVISIBLE);
+            mSendRequestLayout.setVisibility(View.VISIBLE);
+            mSendRequestSettingLayout.setVisibility(View.VISIBLE);
+            mReceiveLayout.setVisibility(View.VISIBLE);
 
-                       mNetwork_tv.setText("");
+            mFindTitleLayout.setVisibility(View.VISIBLE);
+            mRequestTitleLayout.setVisibility(View.VISIBLE);
+            mHandleTitleLayout.setVisibility(View.VISIBLE);
+            mPayLoadClientEditLayout.setVisibility(View.VISIBLE);
 
-               } else if (mCurrentMode == Mode.CLIENT) {
+            mPayLoadServerEditLayout.setVisibility(View.INVISIBLE);
+            mServerButtonLayout.setVisibility(View.INVISIBLE);
 
-                       mFindResourceLayout.setVisibility(View.VISIBLE);
-                       mSendNotificationLayout.setVisibility(View.INVISIBLE);
-                       mSendRequestLayout.setVisibility(View.VISIBLE);
-                       mSendRequestSettingLayout.setVisibility(View.VISIBLE);
-                       mReceiveLayout.setVisibility(View.VISIBLE);
+            mResponseNotificationTitleLayout.setVisibility(View.INVISIBLE);
+            mAdvertiseTitleLayout.setVisibility(View.INVISIBLE);
+            mAdvertiseResourceLayout.setVisibility(View.INVISIBLE);
 
-                       mFindTitleLayout.setVisibility(View.VISIBLE);
-                       mRequestTitleLayout.setVisibility(View.VISIBLE);
-                       mHandleTitleLayout.setVisibility(View.VISIBLE);
-                       mPayLoadClientEditLayout.setVisibility(View.VISIBLE);
+            mSendResponseNotiSettingLayout.setVisibility(View.INVISIBLE);
 
-                       mPayLoadServerEditLayout.setVisibility(View.INVISIBLE);
-                       mServerButtonLayout.setVisibility(View.INVISIBLE);
+            mNetwork_tv.setText("");
+        }
+    }
 
-                       mResponseNotificationTitleLayout.setVisibility(View.INVISIBLE);
-                       mAdvertiseTitleLayout.setVisibility(View.INVISIBLE);
-                       mAdvertiseResourceLayout.setVisibility(View.INVISIBLE);
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
 
-                       mSendResponseNotiSettingLayout.setVisibility(View.INVISIBLE);
+        // Terminate Connectivity Abstraction
+        RM.RMTerminate();
+        android.os.Process.killProcess(android.os.Process.myPid());
+    }
 
-                       mNetwork_tv.setText("");
-               }
-       }
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
 
-       @Override
-       protected void onDestroy() {
-               super.onDestroy();
+        menu.add(0, 1, Menu.NONE, "Start Server");
+        menu.add(0, 2, Menu.NONE, "Start Client");
+        menu.add(0, 3, Menu.NONE, "Select Network");
 
-               // Terminate Connectivity Abstraction
-               RM.RMTerminate();
-               android.os.Process.killProcess(android.os.Process.myPid());
-       }
+        return true;
+    }
 
-       @Override
-       public boolean onCreateOptionsMenu(Menu menu) {
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
 
-               menu.add(0, 1, Menu.NONE, "Start Server");
-               menu.add(0, 2, Menu.NONE, "Start Client");
-               menu.add(0, 3, Menu.NONE, "Select Network");
+        switch (item.getItemId()) {
 
-               return true;
-       }
+        case 1:
 
-       @Override
-       public boolean onOptionsItemSelected(MenuItem item) {
+            RM.RMStartListeningServer();
 
-               switch (item.getItemId()) {
+            if (mSelectedItems.size() == 0) {
+                mCurrentMode = Mode.SERVER;
+                mMode_tv.setText("MODE: " + mCurrentMode.toString());
+                showNetworkView();
 
-               case 1:
+            } else {
+                mCurrentMode = Mode.SERVER;
+                mMode_tv.setText("MODE: " + mCurrentMode.toString());
+                showModeView();
+            }
 
-                       RM.RMStartListeningServer();
+            break;
 
-                       if (mSelectedItems.size() == 0) {
-                               mCurrentMode = Mode.SERVER;
-                               mMode_tv.setText("MODE: " + mCurrentMode.toString());
-                               showNetworkView();
+        case 2:
 
-                       } else {
-                               mCurrentMode = Mode.SERVER;
-                               mMode_tv.setText("MODE: " + mCurrentMode.toString());
-                               showModeView();
-                       }
+            RM.RMStartDiscoveryServer();
 
-                       break;
+            if (mSelectedItems.size() == 0) {
+                mCurrentMode = Mode.CLIENT;
+                mMode_tv.setText("MODE: " + mCurrentMode.toString());
+                showNetworkView();
 
-               case 2:
+            } else {
+                mCurrentMode = Mode.CLIENT;
+                mMode_tv.setText("MODE: " + mCurrentMode.toString());
+                showModeView();
+            }
 
-                       RM.RMStartDiscoveryServer();
+            break;
 
-                       if (mSelectedItems.size() == 0) {
-                               mCurrentMode = Mode.CLIENT;
-                               mMode_tv.setText("MODE: " + mCurrentMode.toString());
-                               showNetworkView();
+        case 3:
 
-                       } else {
-                               mCurrentMode = Mode.CLIENT;
-                               mMode_tv.setText("MODE: " + mCurrentMode.toString());
-                               showModeView();
-                       }
+            showAlertDialog("Select Network");
 
-                       break;
+            break;
+        }
 
-               case 3:
+        return super.onOptionsItemSelected(item);
+    }
 
-                       showAlertDialog("Select Network");
+    private OnClickListener mFindResourceHandler = new OnClickListener() {
 
-                       break;
-               }
+        @Override
+        public void onClick(View v) {
 
-               return super.onOptionsItemSelected(item);
-       }
+            DLog.v(TAG, "FindResource click");
+            RM.RMFindResource(mUri_ed.getText().toString());
 
-       private OnClickListener mFindResourceHandler = new OnClickListener() {
+        }
+    };
 
-               @Override
-               public void onClick(View v) {
+    private OnClickListener mSendResponseHandler = new OnClickListener() {
 
-                       DLog.v(TAG, "FindResource click");
-                       RM.RMFindResource(mUri_ed.getText().toString());
+        @Override
+        public void onClick(View v) {
 
-               }
-       };
+            DLog.v(TAG, "SendResponse click");
+            RM.RMSendResponse(selectedNetwork, isSecured, msgType, responseValue);
+        }
+    };
 
-       private OnClickListener mSendResponseHandler = new OnClickListener() {
+    private OnClickListener mNotifyHandler = new OnClickListener() {
 
-               @Override
-               public void onClick(View v) {
+        @Override
+        public void onClick(View v) {
 
-                       DLog.v(TAG, "SendResponse click");
-                       RM.RMSendResponse(mNotification_ed.getText().toString(),
-                                       mPayload_ed.getText().toString(), selectedNetwork,
-                                       isSecured);
-               }
-       };
+            DLog.v(TAG, "SendNotification click");
+            RM.RMSendNotification(mNotification_ed.getText().toString(),
+                    mPayload_ed.getText().toString(), selectedNetwork,
+                    isSecured);
+        }
+    };
 
-       private OnClickListener mNotifyHandler = new OnClickListener() {
+    private OnClickListener mAdvertiseResourceHandler = new OnClickListener() {
 
-               @Override
-               public void onClick(View v) {
+        @Override
+        public void onClick(View v) {
 
-                       DLog.v(TAG, "SendNotification click");
-                       RM.RMSendNotification(mNotification_ed.getText().toString(),
-                                       mPayload_ed.getText().toString(), selectedNetwork,
-                                       isSecured);
-               }
-       };
+            DLog.v(TAG, "AdvertiseResource click");
+            RM.RMAdvertiseResource(mAdvertise_ed.getText().toString(),
+                    selectedNetwork);
+        }
+    };
 
-       private OnClickListener mAdvertiseResourceHandler = new OnClickListener() {
+    private OnClickListener mSendRequestHandler = new OnClickListener() {
 
-               @Override
-               public void onClick(View v) {
+        @Override
+        public void onClick(View v) {
 
-                       DLog.v(TAG, "AdvertiseResource click");
-                       RM.RMAdvertiseResource(mNotification_ed.getText().toString(),
-                                       selectedNetwork);
-               }
-       };
+            DLog.v(TAG, "SendRequest click");
+            RM.RMSendRequest(mReqData_ed.getText().toString(), mPayload_ed
+                    .getText().toString(), selectedNetwork, isSecured, msgType);
+        }
+    };
 
-       private OnClickListener mSendRequestHandler = new OnClickListener() {
+    private OnClickListener mSendRequestSettingHandler = new OnClickListener() {
 
-               @Override
-               public void onClick(View v) {
+        @Override
+        public void onClick(View v) {
 
-                       DLog.v(TAG, "SendRequest click");
-                       RM.RMSendRequest(mReqData_ed.getText().toString(), mPayload_ed
-                                       .getText().toString(), selectedNetwork, isSecured, msgType);
-               }
-       };
+            checkMsgSecured("Select DTLS Type");
+            checkMsgType("Select Msg Type");
+        }
+    };
 
-       private OnClickListener mSendRequestSettingHandler = new OnClickListener() {
+    private OnClickListener mSendResponseNotiSettingHandler = new OnClickListener() {
 
-               @Override
-               public void onClick(View v) {
+        @Override
+        public void onClick(View v) {
 
-                       checkMsgSecured("Select DTLS Type");
-                       checkMsgType("Select Msg Type");
-               }
-       };
+            checkMsgSecured("Select DTLS Type");
+            checkMsgType("Select Msg Type");
+            checkResponseResult("Select Value of Response Result");
+        }
+    };
 
-       private OnClickListener mSendResponseNotiSettingHandler = new OnClickListener() {
+    private OnClickListener mResponseHandler = new OnClickListener() {
 
-               @Override
-               public void onClick(View v) {
+        @Override
+        public void onClick(View v) {
 
-                       checkMsgSecured("Select DTLS Type");
-               }
-       };
+            RM.RMHandleRequestResponse();
+        }
+    };
 
-       private OnClickListener mResponseHandler = new OnClickListener() {
+    private void showAlertDialog(String title) {
 
-               @Override
-               public void onClick(View v) {
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+        builder.setTitle(title)
+                .setMultiChoiceItems(mCheckBoxItems, null,
+                        new DialogInterface.OnMultiChoiceClickListener() {
 
-                       RM.RMHandleRequestResponse();
-               }
-       };
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which, boolean isChecked) {
 
-       private void showAlertDialog(String title) {
+                                if (isChecked) {
 
-               AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
-               builder.setTitle(title)
-                               .setMultiChoiceItems(mCheckBoxItems, null,
-                                               new DialogInterface.OnMultiChoiceClickListener() {
+                                    mSelectedItems.add(which);
 
-                                                       @Override
-                                                       public void onClick(DialogInterface dialog,
-                                                                       int which, boolean isChecked) {
+                                } else if (mSelectedItems.contains(which)) {
 
-                                                               if (isChecked) {
+                                    mSelectedItems.remove(Integer
+                                            .valueOf(which));
+                                }
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
 
-                                                                       mSelectedItems.add(which);
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
 
-                                                               } else if (mSelectedItems.contains(which)) {
-
-                                                                       mSelectedItems.remove(Integer
-                                                                                       .valueOf(which));
-                                                               }
-                                                       }
-                                               })
-                               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
-                                       @Override
-                                       public void onClick(DialogInterface dialog, int which) {
-
-                                               int interestedNetwork = 0;
-
-                                               for (int i = 0; i < mSelectedItems.size(); i++) {
-
-                                                       if (mSelectedItems.get(i) == Network.WIFI.ordinal()) {
-                                                               interestedNetwork |= CA_WIFI;
-                                                       } else if (mSelectedItems.get(i) == Network.EDR
-                                                                       .ordinal()) {
-                                                               interestedNetwork |= CA_EDR;
-                                                       } else if (mSelectedItems.get(i) == Network.LE
-                                                                       .ordinal()) {
-                                                               interestedNetwork |= CA_LE;
-                                                       }
-                                               }
-
-                                               RM.RMSelectNetwork(interestedNetwork);
-                                               selectedNetwork = interestedNetwork;
-                                       }
-                               }).show();
-
-               mSelectedItems.clear();
-       }
-
-       private void checkMsgSecured(String title) {
-
-               AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
-
-               builder.setTitle(title)
-                               .setSingleChoiceItems(mDTLSCheckBoxItems, -1,
-                                               new DialogInterface.OnClickListener() {
-
-                                                       @Override
-                                                       public void onClick(DialogInterface dialog,
-                                                                       int which) {
-                                                               selectedItem = which;
-                                                       }
-                                               })
-                               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
-                                       @Override
-                                       public void onClick(DialogInterface dialog, int which) {
-
-                                               if (selectedItem == DTLS.SECURED.ordinal()) {
-                                                       isSecured = 1;
-                                                       DLog.v(TAG, "Send secured message");
-
-                                                       mPayLoadClientEditLayout
-                                                                       .setVisibility(View.INVISIBLE);
-
-                                                       mPayLoadServerEditLayout
-                                                                       .setVisibility(View.INVISIBLE);
-
-                                               } else if (selectedItem == DTLS.UNSECURED.ordinal()) {
-                                                       isSecured = 0;
-                                                       DLog.v(TAG, "Send unsecured message");
-
-                                                       if (mCurrentMode == Mode.SERVER) {
-                                                               mPayLoadServerEditLayout
-                                                                               .setVisibility(View.VISIBLE);
-                                                       } else if (mCurrentMode == Mode.CLIENT) {
-                                                               mPayLoadClientEditLayout
-                                                                               .setVisibility(View.VISIBLE);
-                                                       }
-                                               }
-                                       }
-
-                               }).show();
-       }
-
-       private void checkMsgType(String title) {
-
-               AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
-               builder.setTitle(title)
-                               .setSingleChoiceItems(mMsgTyleCheckBoxItems, -1,
-                                               new DialogInterface.OnClickListener() {
-
-                                                       @Override
-                                                       public void onClick(DialogInterface dialog,
-                                                                       int which) {
-                                                               selectedItem = which;
-                                                       }
-                                               })
-                               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
-                                       @Override
-                                       public void onClick(DialogInterface dialog, int which) {
-
-                                               if (selectedItem == MsgType.CON.ordinal()) {
-                                                       msgType = 0;
-                                                       DLog.v(TAG, "Message Type is CON");
-
-                                               } else if (selectedItem == MsgType.NON.ordinal()) {
-                                                       msgType = 1;
-                                                       DLog.v(TAG, "Message Type is NON");
-                                               }
-
-                                       }
-                               }).show();
-       }
-
-       public void OnResponseReceived(String subject, String receivedData) {
-               String callbackData = subject + receivedData;
-               DLog.v(TAG, callbackData);
-
-       }
+                        int interestedNetwork = 0;
+
+                        for (int i = 0; i < mSelectedItems.size(); i++) {
+
+                            if (mSelectedItems.get(i) == Network.WIFI.ordinal()) {
+                                interestedNetwork |= CA_WIFI;
+                            } else if (mSelectedItems.get(i) == Network.EDR
+                                    .ordinal()) {
+                                interestedNetwork |= CA_EDR;
+                            } else if (mSelectedItems.get(i) == Network.LE
+                                    .ordinal()) {
+                                interestedNetwork |= CA_LE;
+                            }
+                        }
+
+                        RM.RMSelectNetwork(interestedNetwork);
+                        selectedNetwork = interestedNetwork;
+                    }
+                }).show();
+
+        mSelectedItems.clear();
+    }
+
+    private void checkMsgSecured(String title) {
+
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+
+        builder.setTitle(title)
+                .setSingleChoiceItems(mDTLSCheckBoxItems, isSecured,
+                        new DialogInterface.OnClickListener() {
+
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which) {
+                                selectedItem = which;
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+
+                        if (selectedItem == DTLS.SECURED.ordinal()) {
+                            isSecured = 1;
+                            DLog.v(TAG, "Send secured message");
+
+                            mPayLoadClientEditLayout
+                                    .setVisibility(View.INVISIBLE);
+
+                            mPayLoadServerEditLayout
+                                    .setVisibility(View.INVISIBLE);
+
+                        } else if (selectedItem == DTLS.UNSECURED.ordinal()) {
+                            isSecured = 0;
+                            DLog.v(TAG, "Send unsecured message");
+
+                            if (mCurrentMode == Mode.SERVER) {
+                                mPayLoadServerEditLayout
+                                        .setVisibility(View.VISIBLE);
+                            } else if (mCurrentMode == Mode.CLIENT) {
+                                mPayLoadClientEditLayout
+                                        .setVisibility(View.VISIBLE);
+                            }
+                        }
+                    }
+
+                }).show();
+    }
+
+    private void checkMsgType(String title) {
+
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+        builder.setTitle(title)
+                .setSingleChoiceItems(mMsgTyleCheckBoxItems, msgType,
+                        new DialogInterface.OnClickListener() {
+
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which) {
+                                selectedItem = which;
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+
+                        if (selectedItem == MsgType.CON.ordinal()) {
+                            msgType = 0;
+                            DLog.v(TAG, "Message Type is CON");
+
+                        } else if (selectedItem == MsgType.NON.ordinal()) {
+                            msgType = 1;
+                            DLog.v(TAG, "Message Type is NON");
+                        } else if (selectedItem == MsgType.ACK.ordinal()) {
+                            msgType = 2;
+                            DLog.v(TAG, "Message Type is ACK");
+                        } else if (selectedItem == MsgType.RESET.ordinal()) {
+                            msgType = 3;
+                            DLog.v(TAG, "Message Type is RESET");
+                        }
+                    }
+                }).show();
+    }
+
+    private void checkResponseResult(String title) {
+
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+        builder.setTitle(title)
+                .setSingleChoiceItems(mResponseResultCheckBoxItems, selectedResponseValue,
+                        new DialogInterface.OnClickListener() {
+
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which) {
+                                selectedResponseValue = which;
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+
+                        if (selectedResponseValue == ResponseResult.CA_SUCCESS.ordinal()) {
+                            responseValue = 200;
+                            DLog.v(TAG, "Response Value is CA_SUCCESS");
+                        } else if (selectedResponseValue == ResponseResult.CA_CREATED
+                                .ordinal()) {
+                            responseValue = 201;
+                            DLog.v(TAG, "Response Value is CA_CREATED");
+                        } else if (selectedResponseValue == ResponseResult.CA_DELETED
+                                .ordinal()) {
+                            responseValue = 202;
+                            DLog.v(TAG, "Response Value is CA_DELETED");
+                        } else if (selectedResponseValue == ResponseResult.CA_EMPTY
+                                .ordinal()) {
+                            responseValue = 231;
+                            DLog.v(TAG, "Response Value is CA_EMPTY");
+                        } else if (selectedResponseValue == ResponseResult.CA_BAD_REQ
+                                .ordinal()) {
+                            responseValue = 400;
+                            DLog.v(TAG, "Response Value is CA_BAD_REQ");
+                        } else if (selectedResponseValue == ResponseResult.CA_BAD_OPT
+                                .ordinal()) {
+                            responseValue = 402;
+                            DLog.v(TAG, "Response Value is CA_BAD_OPT");
+                        } else if (selectedResponseValue == ResponseResult.CA_NOT_FOUND
+                                .ordinal()) {
+                            responseValue = 404;
+                            DLog.v(TAG, "Response Value is CA_NOT_FOUND");
+                        } else if (selectedResponseValue == ResponseResult.CA_RETRANSMIT_TIMEOUT
+                                .ordinal()) {
+                            responseValue = 531;
+                            DLog.v(TAG, "Response Value is CA_RETRANSMIT_TIMEOUT");
+                        }
+                    }
+                }).show();
+    }
+
+    public void OnResponseReceived(String subject, String receivedData) {
+        String callbackData = subject + receivedData;
+        DLog.v(TAG, callbackData);
+
+    }
 }
\ No newline at end of file
index 58c7bb7..1733b57 100644 (file)
@@ -1,4 +1,3 @@
-
 package com.iotivity.service;
 
 import android.content.Context;
@@ -8,15 +7,15 @@ public class RMInterface {
     static {
         // Load RI JNI interface
         System.loadLibrary("RMInterface");
-        
+
         // Load CA JNI interface
         System.loadLibrary("CAInterface");
     }
 
     private com.iotivity.service.MainActivity mResponseListener = null;
-    
+
     public native void setNativeResponseListener(Object listener);
-    
+
     public native void RMInitialize(Context context);
 
     public native void RMTerminate();
@@ -29,28 +28,31 @@ public class RMInterface {
 
     public native void RMFindResource(String uri);
 
-    public native void RMSendRequest(String uri, String payload, int selectedNetwork, int isSecured, int msgType);
+    public native void RMSendRequest(String uri, String payload,
+            int selectedNetwork, int isSecured, int msgType);
 
-    public native void RMSendResponse(String uri, String payload, int selectedNetwork, int isSecured);
+    public native void RMSendResponse(int selectedNetwork, int isSecured,
+            int msgType, int responseValue);
 
-    public native void RMAdvertiseResource(String advertiseResource, int selectedNetwork);
-    
-    public native void RMSendNotification(String uri, String payload, int selectedNetwork, int isSecured);
+    public native void RMAdvertiseResource(String advertiseResource,
+            int selectedNetwork);
+
+    public native void RMSendNotification(String uri, String payload,
+            int selectedNetwork, int isSecured);
 
     public native void RMSelectNetwork(int interestedNetwork);
 
     public native void RMHandleRequestResponse();
-    
+
     public void setResponseListener(com.iotivity.service.MainActivity listener) {
-       mResponseListener = listener;
-       setNativeResponseListener(this);
+        mResponseListener = listener;
+        setNativeResponseListener(this);
     }
-    
+
     private void OnResponseReceived(String subject, String receivedData) {
-       
-       if (null != mResponseListener) {
-               mResponseListener.OnResponseReceived(subject, receivedData);
-       }
+        if (null != mResponseListener) {
+            mResponseListener.OnResponseReceived(subject, receivedData);
+        }
     }
-    
+
 }
\ No newline at end of file
index 5983522..68e46bf 100644 (file)
@@ -673,24 +673,50 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *
 
 void send_response(CARemoteEndpoint_t *endpoint, const CAInfo_t* info)
 {
+    char buf[MAX_BUF_LEN];
+    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
 
     printf("============");
+    printf("Select Message Type");
+    printf("CON: 0");
+    printf("NON: 1");
+    printf("ACK: 2");
+    printf("RESET: 3");
+
+
+    int16_t len = 0;
+    getData(buf, (int16_t)sizeof(buf), &len);
+    int32_t messageType = buf[0] - '0';
+    int32_t respCode =231 ;
+
+    if(messageType != 3)
+    {
+        printf("============");
+        printf("Select Resp code:");
+        printf("Success: 200");
+        printf("Created: 201");
+        printf("Deleted: 202");
+        printf("Empty  : 231");
+        printf("BadReq : 400");
+        printf("BadOpt : 402");
+        printf("NotFnd : 404");
+        printf("Timeout: 531");
+       getData(buf, (int16_t)sizeof(buf), &len);
+       respCode = atoi(buf);
+    }
 
     CAInfo_t responseData;
     memset(&responseData, 0, sizeof(CAInfo_t));
-    responseData.type =
-            (info != NULL) ?
-                    ((info->type == CA_MSG_CONFIRM) ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM) :
-                    CA_MSG_NONCONFIRM;
+    responseData.type = (CAMessageType_t)messageType;
+
     responseData.messageId = (info != NULL) ? info->messageId : 0;
     responseData.token = (info != NULL) ? (CAToken_t)info->token : (CAToken_t)"";
     responseData.payload = (CAPayload_t)"response payload";
 
     CAResponseInfo_t responseInfo;
     memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
-    responseInfo.result = (CAResponseResult_t)203;
+    responseInfo.result = (CAResponseResult_t)respCode;
     responseInfo.info = responseData;
-
     // send request (connectivityType from remoteEndpoint of request Info)
     CAResult_t res = CASendResponse(endpoint, &responseInfo);
     if(res != CA_STATUS_OK)
index 172d830..60108c3 100644 (file)
@@ -60,7 +60,6 @@ void start_discovery_server();
 void find_resource();
 void send_request();
 void send_request_all();
-void send_response();
 void advertise_resource();
 void send_notification();
 void select_network();
@@ -73,6 +72,7 @@ void send_secure_request();
 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
 void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token);
+void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info);
 void get_resource_uri(char *URI, char *resourceURI, int length);
 int get_secure_information(CAPayload_t payLoad);
 
@@ -1058,6 +1058,7 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *
     printf("response result : %d\n", responseInfo->result);
     printf("Data: %s\n", responseInfo->info.payload);
     printf("Message type: %s\n", gMessageType[responseInfo->info.type]);
+    printf("Token: %s\n", responseInfo->info.token);
     if (responseInfo->info.options)
     {
         uint32_t len = responseInfo->info.numOptions;
@@ -1086,21 +1087,51 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *
 
 void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
 {
+    char buf[MAX_BUF_LEN];
+
     printf("entering send_response\n");
 
+    printf("\n=============================================\n");
+    printf("\tselect message type\n");
+    printf("CA_MSG_CONFIRM      : 0\n");
+    printf("CA_MSG_NONCONFIRM   : 1\n");
+    printf("CA_MSG_ACKNOWLEDGE  : 2\n");
+    printf("CA_MSG_RESET        : 3\n");
+    printf("select : ");
+
+    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+    gets(buf);
+
+    int messageType = buf[0] - '0';
+    int responseCode = 231 ;
+    if(messageType != 3)
+    {
+
+        printf("\n=============================================\n");
+        printf("\tselect response code\n");
+        printf("CA_SUCCESS              : 200\n");
+        printf("CA_CREATED              : 201\n");
+        printf("CA_DELETED              : 202\n");
+        printf("CA_EMPTY                : 231\n");
+        printf("CA_BAD_REQ              : 400\n");
+        printf("CA_BAD_OPT              : 402\n");
+        printf("CA_NOT_FOUND            : 404\n");
+        printf("CA_RETRANSMIT_TIMEOUT   : 531\n");
+        printf("select : ");
+        scanf("%d", &responseCode);
+    }
     CAInfo_t responseData;
     memset(&responseData, 0, sizeof(CAInfo_t));
-    responseData.type =
-        (info != NULL) ?
-        ((info->type == CA_MSG_CONFIRM) ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM) :
-            CA_MSG_NONCONFIRM;
+    responseData.type = messageType;
     responseData.messageId = (info != NULL) ? info->messageId : 0;
-    responseData.token = (info != NULL) ? info->token : "";
-    responseData.payload = "response payload";
-
+    if(messageType != 3)
+    {
+        responseData.token = (info != NULL) ? info->token : "";
+        responseData.payload = "response payload";
+    }
     CAResponseInfo_t responseInfo;
     memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
-    responseInfo.result = 203;
+    responseInfo.result = responseCode;
     responseInfo.info = responseData;
 
     if (CA_TRUE == endpoint->isSecured)
index 71e09ea..1119e45 100644 (file)
@@ -985,6 +985,7 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *
     printf("response result : %d\n", responseInfo->result);
     printf("Data: %s\n", responseInfo->info.payload);
     printf("Message type: %s\n", gMessageType[responseInfo->info.type]);
+    printf("Token: %s\n", responseInfo->info.token);
     if (responseInfo->info.options)
     {
         uint32_t len = responseInfo->info.numOptions;
@@ -1013,21 +1014,49 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *
 
 void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
 {
+    char buf[MAX_BUF_LEN];
+
     printf("entering send_response\n");
 
+    printf("\n=============================================\n");
+    printf("\tselect message type\n");
+    printf("CA_MSG_CONFIRM      : 0\n");
+    printf("CA_MSG_NONCONFIRM   : 1\n");
+    printf("CA_MSG_ACKNOWLEDGE  : 2\n");
+    printf("CA_MSG_RESET        : 3\n");
+    printf("select : ");
+
+    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+    gets(buf);
+
+    int messageType = buf[0] - '0';
+    int responseCode = 231 ;
+    if(messageType != 3)
+    {
+
+        printf("\n=============================================\n");
+        printf("\tselect response code\n");
+        printf("CA_SUCCESS              : 200\n");
+        printf("CA_CREATED              : 201\n");
+        printf("CA_DELETED              : 202\n");
+        printf("CA_EMPTY                : 231\n");
+        printf("CA_BAD_REQ              : 400\n");
+        printf("CA_BAD_OPT              : 402\n");
+        printf("CA_NOT_FOUND            : 404\n");
+        printf("CA_RETRANSMIT_TIMEOUT   : 531\n");
+        printf("select : ");
+        scanf("%d", &responseCode);
+    }
     CAInfo_t responseData;
     memset(&responseData, 0, sizeof(CAInfo_t));
-    responseData.type =
-        (info != NULL) ?
-        ((info->type == CA_MSG_CONFIRM) ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM) :
-            CA_MSG_NONCONFIRM;
+    responseData.type = messageType;
     responseData.messageId = (info != NULL) ? info->messageId : 0;
     responseData.token = (info != NULL) ? info->token : "";
     responseData.payload = "response payload";
 
     CAResponseInfo_t responseInfo;
     memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
-    responseInfo.result = 203;
+    responseInfo.result = responseCode;
     responseInfo.info = responseData;
 
     if (CA_TRUE == endpoint->isSecured)
index b2efaeb..f9fe548 100644 (file)
@@ -120,6 +120,7 @@ static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, void *pdu, uin
 
 static void CADataDestroyer(void *data, uint32_t size)
 {
+    OIC_LOG(DEBUG, TAG, "CADataDestroyer is ran!");
     CAData_t *cadata = (CAData_t *) data;
 
     if (cadata == NULL)
@@ -366,7 +367,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
             }
             memset(endpoint->resourceUri, 0, strlen(uri) + 1);
             memcpy(endpoint->resourceUri, uri, strlen(uri));
-            OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
+            OIC_LOG_V(DEBUG, TAG, "resource URI : %s", endpoint->resourceUri);
         }
         // store the data at queue.
         CAData_t *cadata = NULL;
@@ -410,12 +411,17 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
 
                 OIC_LOG_V(DEBUG, TAG, "Response- list: %s", ResInfo->info.options[i].optionData);
             }
-            if (NULL != ResInfo->info.payload)
-            {
-                OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
-            } OIC_LOG_V(DEBUG, TAG, "Response- code: %d", ResInfo->result);
         }
 
+        if (NULL != ResInfo->info.payload)
+        {
+            OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
+        }
+
+        OIC_LOG_V(DEBUG, TAG, "Response- response code: %d", ResInfo->result);
+        OIC_LOG_V(DEBUG, TAG, "Response- token : %s", ResInfo->info.token);
+        OIC_LOG_V(DEBUG, TAG, "Response- msgID: %d", ResInfo->info.messageId);
+
         if (NULL != endpoint)
         {
             endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
@@ -428,7 +434,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
             }
             memset(endpoint->resourceUri, 0, strlen(uri) + 1);
             memcpy(endpoint->resourceUri, uri, strlen(uri));
-            OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
+            OIC_LOG_V(DEBUG, TAG, "resource URI : %s", endpoint->resourceUri);
         }
 
         // store the data at queue.
@@ -448,12 +454,20 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
         cadata->type = SEND_TYPE_UNICAST;
         cadata->remoteEndpoint = endpoint;
         cadata->requestInfo = NULL;
+
+        // for retransmission
+        void *retransmissionPdu = NULL;
+        CARetransmissionReceivedData(&gRetransmissionContext, endpoint, pdu->hdr, pdu->length, &retransmissionPdu);
+
+        // get token from saved data in retransmission list
+        if(retransmissionPdu && CA_EMPTY == code)
+        {
+            CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu, &(ResInfo->info));
+            OICFree(retransmissionPdu);
+        }
         cadata->responseInfo = ResInfo;
 
         CAQueueingThreadAddData(&gReceiveThread, cadata, sizeof(CAData_t));
-
-        // for retransmission
-        CARetransmissionReceivedData(&gRetransmissionContext, endpoint, pdu->hdr, pdu->length);
     }
 
     if(pdu)
@@ -504,6 +518,7 @@ void CAHandleRequestResponseCallbacks()
     {
         if (gRequestHandler)
         {
+            OIC_LOG_V(DEBUG, TAG, "callback will be sent : %d", td->requestInfo->info.numOptions);
             gRequestHandler(rep, td->requestInfo);
         }
 
@@ -912,7 +927,7 @@ void CATerminateMessageHandler()
     if(gReceiveThread.threadMutex != NULL) {
        #ifndef SINGLE_HANDLE// This will be enabled when RI supports multi threading
         // CAQueueingThreadStop(&gReceiveThread);
-       #endif  
+       #endif
         CAQueueingThreadDestroy(&gReceiveThread);
     }
 
index 78996e6..e98b535 100644 (file)
@@ -86,14 +86,15 @@ static void CAProcessData(CAData_t *data)
             OIC_LOG(DEBUG, TAG, "reqInfo avlbl");
 
             pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri,
-                                               data->requestInfo->method, data->requestInfo->info);
+                                               data->requestInfo->method,
+                                               data->requestInfo->info);
         }
         else if (data->responseInfo != NULL)
         {
             OIC_LOG(DEBUG, TAG, "resInfo avlbl");
-
             pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri,
-                                               data->responseInfo->result, data->responseInfo->info);
+                                               data->responseInfo->result,
+                                               data->responseInfo->info);
         }
         else
         {
@@ -198,7 +199,7 @@ static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, void *pdu, uin
 }
 
 static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
-    uint32_t dataLen)
+                                     uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TAG, "IN");
     VERIFY_NON_NULL_VOID(data, TAG, "data");
@@ -208,6 +209,12 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
     pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
     //OICFree(data);
 
+    if(NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "pdu is null");
+        return;
+    }
+
     char uri[CA_MAX_URI_LENGTH] = { 0, };
 
     if (CA_GET == code || CA_POST == code  || CA_PUT == code  || CA_DELETE == code )
@@ -241,7 +248,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
 
         OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
         OIC_LOG_V(DEBUG, TAG, "Request- token : %s", ReqInfo->info.token);
-
+        OIC_LOG_V(DEBUG, TAG, "Request- msgID : %d", ReqInfo->info.messageId);
         if (NULL != endpoint)
         {
             endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
@@ -312,14 +319,23 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
         }
 
+        // for retransmission
+        void *retransmissionPdu = NULL;
+        CARetransmissionReceivedData(&gRetransmissionContext, endpoint, pdu->hdr, pdu->length,
+                                     &retransmissionPdu);
+
+        // get token from saved data in retransmission list
+        if(retransmissionPdu && CA_EMPTY == code)
+        {
+            CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu, &(ResInfo->info));
+            OICFree(retransmissionPdu);
+        }
+
         if (ResInfo != NULL)
         {
             if (gResponseHandler)
             {
                 gResponseHandler(endpoint, ResInfo);
-
-                // for retransmission
-                CARetransmissionReceivedData(&gRetransmissionContext, endpoint, pdu->hdr, pdu->length);
             }
             CADestroyResponseInfoInternal(ResInfo);
         }
index 32f09e7..b852ae9 100644 (file)
-/******************************************************************\r
- *\r
- * Copyright 2014 Samsung Electronics All Rights Reserved.\r
- *\r
- *\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *      http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- *\r
- ******************************************************************/\r
-\r
-#include <stdio.h>\r
-#include <stdlib.h>\r
-#include <string.h>\r
-#include <time.h>\r
-\r
-#include "caprotocolmessage.h"\r
-#include "logger.h"\r
-#include "oic_malloc.h"\r
-\r
-#define TAG "CA"\r
-\r
-#define CA_FLAGS_BLOCK 0x01\r
-#define CA_BUFSIZE 128\r
-#define CA_COAP_MESSAGE_CON 0\r
-\r
-static int32_t SEED = 0;\r
-\r
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,\r
-                                 char *outUri)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu IN");\r
-\r
-    if (NULL == pdu)\r
-        return 0;\r
-\r
-    uint32_t code = CA_NOT_FOUND;\r
-    CAGetRequestPDUInfo(pdu, &code, &(outReqInfo->info), outUri);\r
-    outReqInfo->method = code;\r
-    OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu OUT");\r
-    return 1;\r
-}\r
-\r
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,\r
-                                  char *outUri)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu IN");\r
-    if (NULL == pdu)\r
-        return 0;\r
-\r
-    uint32_t code = CA_NOT_FOUND;\r
-    CAGetRequestPDUInfo(pdu, &code, &(outResInfo->info), outUri);\r
-    outResInfo->result = code;\r
-    OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu OUT");\r
-    return 1;\r
-}\r
-\r
-coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAGeneratePdu IN");\r
-\r
-    coap_pdu_t *pdu;\r
-    char *coapUri = NULL;\r
-    uint32_t coapHeaderLength = 12;\r
-    uint32_t length;\r
-    coap_list_t *optlist = NULL;\r
-\r
-    if (NULL == uri)\r
-        return NULL;\r
-\r
-    length = strlen(uri);\r
-    if (CA_MAX_URI_LENGTH < length)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "check URI length..");\r
-        return NULL;\r
-    }\r
-\r
-    uint32_t uriLength = length + coapHeaderLength + 1;\r
-    coapUri = (char *) OICMalloc(uriLength);\r
-    if (NULL == coapUri)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAGeneratePdu, Memory allocation failed !");\r
-        return NULL;\r
-    }\r
-    memset(coapUri, 0, uriLength);\r
-\r
-    if (NULL != coapUri)\r
-    {\r
-        strcat(coapUri, "coap://[::]/");\r
-        strcat(coapUri, uri);\r
-\r
-        // parsing options in URI\r
-        CAParseURI(coapUri, &optlist);\r
-        OICFree(coapUri);\r
-        coapUri = NULL;\r
-\r
-        // parsing options in HeadOption\r
-        CAParseHeadOption(code, info, &optlist);\r
-    }\r
-\r
-    if (NULL != info.payload) // payload is include in request / response\r
-    {\r
-        if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload, info)))\r
-            return NULL;\r
-    }\r
-    else // payload is not include in request / response\r
-    {\r
-        if (!(pdu = CACreatePDUforRequest((code_t) code, optlist, info)))\r
-            return NULL;\r
-    }\r
-\r
-    // free option list\r
-    coap_delete_list(optlist);\r
-\r
-    // pdu print method : coap_show_pdu(pdu);\r
-    OIC_LOG(DEBUG, TAG, "CAGeneratePdu OUT");\r
-    return pdu;\r
-}\r
-\r
-coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAParsePDU IN");\r
-    coap_pdu_t *outpdu = coap_new_pdu();\r
-\r
-    coap_pdu_parse((unsigned char *) data, length, outpdu);\r
-    (*outCode) = (uint32_t) outpdu->hdr->code;\r
-    OIC_LOG(DEBUG, TAG, "CAParsePDU OUT");\r
-    return outpdu;\r
-}\r
-\r
-coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options,\r
-        const char *payload, const CAInfo_t info)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload IN");\r
-\r
-    coap_pdu_t *pdu;\r
-    coap_list_t *opt;\r
-\r
-    uint32_t CAFlags = 0;\r
-    coap_block_t CABlock =\r
-    { .num = 0, .m = 0, .szx = 6 };\r
-\r
-    if (!(pdu = coap_new_pdu()))\r
-        return NULL;\r
-\r
-    unsigned short message_id;\r
-\r
-    if (info.messageId == 0)\r
-    {\r
-        /* initialize message id */\r
-        prng((unsigned char * )&message_id, sizeof(unsigned short));\r
-        ++message_id;\r
-\r
-        OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);\r
-    }\r
-    else\r
-    {\r
-        /* use saved message id */\r
-        message_id = info.messageId;\r
-    }\r
-\r
-    pdu->hdr->type = info.type;\r
-    pdu->hdr->id = htons(message_id);\r
-    pdu->hdr->code = code;\r
-\r
-    if (info.token)\r
-    {\r
-        pdu->hdr->token_length = CA_MAX_TOKEN_LEN;\r
-        if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "cannot add token to request");\r
-        }\r
-    }\r
-    for (opt = options; opt; opt = opt->next)\r
-    {\r
-        OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.", COAP_OPTION_DATA(*(coap_option * )opt->data));\r
-        coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option * )opt->data),\r
-                        COAP_OPTION_LENGTH(*(coap_option * )opt->data),\r
-                        COAP_OPTION_DATA(*(coap_option * )opt->data));\r
-    }\r
-\r
-    if (NULL != payload)\r
-    {\r
-        uint32_t len = strlen(payload);\r
-        if ((CAFlags & CA_FLAGS_BLOCK) == 0)\r
-        {\r
-            OIC_LOG_V(DEBUG, TAG, "coap_add_data, payload: %s", payload);\r
-            coap_add_data(pdu, len, (const unsigned char *) payload);\r
-        }\r
-        else\r
-        {\r
-            OIC_LOG_V(DEBUG, TAG, "coap_add_block, payload: %s", payload);\r
-            coap_add_block(pdu, len, (const unsigned char *) payload, CABlock.num, CABlock.szx);\r
-        }\r
-    }\r
-    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload OUT");\r
-    return pdu;\r
-}\r
-\r
-coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,\r
-                                  const CAInfo_t info)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest IN");\r
-\r
-    coap_pdu_t *pdu;\r
-    coap_list_t *opt;\r
-\r
-    if (!(pdu = coap_new_pdu()))\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "Out of memory");\r
-        return NULL;\r
-    }\r
-\r
-    unsigned short message_id;\r
-\r
-    if (info.messageId == 0)\r
-    {\r
-        /* initialize message id */\r
-        prng((unsigned char * )&message_id, sizeof(unsigned short));\r
-        ++message_id;\r
-\r
-        OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);\r
-    }\r
-    else\r
-    {\r
-        /* use saved message id */\r
-        message_id = info.messageId;\r
-    }\r
-\r
-    pdu->hdr->type = info.type;\r
-    pdu->hdr->id = htons(message_id);\r
-    pdu->hdr->code = code;\r
-\r
-    OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, strlen(info.token));\r
-    pdu->hdr->token_length = CA_MAX_TOKEN_LEN;\r
-\r
-    if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "cannot add token to request");\r
-    }\r
-\r
-    for (opt = options; opt; opt = opt->next)\r
-    {\r
-        coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option * )opt->data),\r
-                        COAP_OPTION_LENGTH(*(coap_option * )opt->data),\r
-                        COAP_OPTION_DATA(*(coap_option * )opt->data));\r
-    }\r
-    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest OUT");\r
-    return pdu;\r
-}\r
-\r
-void CAParseURI(const char *uriInfo, coap_list_t **optlist)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAParseURI IN");\r
-\r
-    unsigned char portbuf[2];\r
-    unsigned char _buf[CA_BUFSIZE];\r
-    unsigned char *buf = _buf;\r
-    coap_uri_t uri;\r
-    size_t buflen;\r
-    uint32_t res;\r
-\r
-    OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);\r
-\r
-    /* split arg into Uri-* options */\r
-    coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);\r
-\r
-    if (uri.port != COAP_DEFAULT_PORT)\r
-    {\r
-        coap_insert(optlist,\r
-                    CACreateNewOptionNode(COAP_OPTION_URI_PORT,\r
-                                          coap_encode_var_bytes(portbuf, uri.port), portbuf),\r
-                    CAOrderOpts);\r
-    }\r
-\r
-    if (uri.path.length)\r
-    {\r
-        buflen = CA_BUFSIZE;\r
-        res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);\r
-\r
-        while (res--)\r
-        {\r
-            coap_insert(optlist,\r
-                        CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf),\r
-                                              COAP_OPT_VALUE(buf)), CAOrderOpts);\r
-            buf += COAP_OPT_SIZE(buf);\r
-        }\r
-    }\r
-\r
-    if (uri.query.length)\r
-    {\r
-        buflen = CA_BUFSIZE;\r
-        buf = _buf;\r
-        res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);\r
-\r
-        while (res--)\r
-        {\r
-            coap_insert(optlist,\r
-                        CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf),\r
-                                              COAP_OPT_VALUE(buf)), CAOrderOpts);\r
-\r
-            buf += COAP_OPT_SIZE(buf);\r
-        }\r
-    }\r
-    OIC_LOG(DEBUG, TAG, "CAParseURI OUT");\r
-}\r
-\r
-void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAParseHeadOption IN");\r
-    OIC_LOG_V(DEBUG, TAG, "start parse Head Option : %d", info.numOptions);\r
-\r
-    uint32_t i;\r
-    for (i = 0; i < info.numOptions; i++)\r
-    {\r
-        uint32_t id = info.options[i].optionID;\r
-        if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)\r
-        {\r
-            OIC_LOG_V(DEBUG, TAG, "it is not Header Option : %d", id);\r
-        }\r
-        else\r
-        {\r
-            OIC_LOG_V(DEBUG, TAG, "Head Option ID: %d", info.options[i].optionID);\r
-            OIC_LOG_V(DEBUG, TAG, "Head Option data: %s", info.options[i].optionData);\r
-            OIC_LOG_V(DEBUG, TAG, "Head Option length: %d", info.options[i].optionLength);\r
-\r
-            coap_insert(optlist,\r
-                        CACreateNewOptionNode(info.options[i].optionID,\r
-                                              info.options[i].optionLength,\r
-                                              info.options[i].optionData), CAOrderOpts);\r
-        }\r
-    }\r
-    OIC_LOG(DEBUG, TAG, "CAParseHeadOption OUT");\r
-}\r
-\r
-coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length,\r
-                                   const uint8_t *data)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode IN");\r
-    coap_option *option;\r
-    coap_list_t *node;\r
-\r
-    option = coap_malloc(sizeof(coap_option) + length + 1);\r
-    if (!option)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "Out of memory");\r
-        return NULL;\r
-    }\r
-    memset(option, 0, sizeof(coap_option) + length + 1);\r
-\r
-    COAP_OPTION_KEY(*option) = key;\r
-    COAP_OPTION_LENGTH(*option) = length;\r
-    memcpy(COAP_OPTION_DATA(*option), data, length);\r
-\r
-    /* we can pass NULL here as delete function since option is released automatically  */\r
-    node = coap_new_listnode(option, NULL);\r
-\r
-    if (!node)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "coap_new_listnode returns NULL");\r
-        coap_free(option);\r
-        return NULL;\r
-    }\r
-    //coap_free(option);\r
-    OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode OUT");\r
-    return node;\r
-}\r
-\r
-int CAOrderOpts(void *a, void *b)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAOrderOpts IN");\r
-    if (!a || !b)\r
-    {\r
-        return a < b ? -1 : 1;\r
-    }\r
-\r
-    if (COAP_OPTION_KEY(*(coap_option *)a) < COAP_OPTION_KEY(*(coap_option * )b))\r
-    {\r
-        return -1;\r
-    }\r
-    OIC_LOG(DEBUG, TAG, "CAOrderOpts OUT");\r
-    return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option * )b);\r
-}\r
-\r
-uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAGetOptionCount IN");\r
-    uint32_t count = 0;\r
-    coap_opt_t *option;\r
-\r
-    while ((option = coap_option_next(&opt_iter)))\r
-    {\r
-        if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)\r
-        {\r
-\r
-        }\r
-        else\r
-        {\r
-            count++;\r
-        }\r
-    }\r
-    OIC_LOG(DEBUG, TAG, "CAGetOptionCount OUT");\r
-    return count;\r
-}\r
-\r
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,\r
-                         char *outUri)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo IN");\r
-    char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */\r
-    uint32_t encode = 0;\r
-    coap_opt_iterator_t opt_iter;\r
-    coap_opt_t *option;\r
-    char optionResult[CA_MAX_URI_LENGTH] =\r
-    { 0, };\r
-    uint32_t count = 0, idx = 0;\r
-    uint32_t optionLength = 0;\r
-    uint32_t isfirstsetflag = 0;\r
-\r
-    coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL);\r
-\r
-    memset(optionResult, 0, sizeof(optionResult));\r
-\r
-    // set code\r
-    (*outCode) = (uint32_t) pdu->hdr->code;\r
-\r
-    // init HeaderOption list\r
-    count = CAGetOptionCount(opt_iter);\r
-\r
-    memset(outInfo, 0, sizeof(CAInfo_t));\r
-    outInfo->numOptions = count;\r
-    // set type\r
-    outInfo->type = pdu->hdr->type;\r
-\r
-    // set message id\r
-    outInfo->messageId = ntohs(pdu->hdr->id);\r
-\r
-    if (count > 0)\r
-    {\r
-        outInfo->options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * count);\r
-        if (outInfo->options == NULL)\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");\r
-            return;\r
-        }\r
-        memset(outInfo->options, 0, sizeof(CAHeaderOption_t) * count);\r
-    }\r
-\r
-    while ((option = coap_option_next(&opt_iter)))\r
-    {\r
-\r
-        if (CAGetOptionData((uint8_t *)(COAP_OPT_VALUE(option)),\r
-                            COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf),\r
-                            encode))\r
-        {\r
-            OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);\r
-            if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)\r
-            {\r
-                if (0 == isfirstsetflag)\r
-                {\r
-                    isfirstsetflag = 1;\r
-                    memcpy(optionResult + optionLength, "/", 1);\r
-                    optionLength++;\r
-                    memcpy(optionResult + optionLength, buf, strlen((const char *) buf));\r
-                    optionLength += strlen((const char *) buf);\r
-                }\r
-                else\r
-                {\r
-                    if (COAP_OPTION_URI_PATH == opt_iter.type)\r
-                    {\r
-                        memcpy(optionResult + optionLength, "/", 1);\r
-                        optionLength++;\r
-                    }\r
-                    else if (COAP_OPTION_URI_QUERY == opt_iter.type)\r
-                    {\r
-                        memcpy(optionResult + optionLength, "?", 1);\r
-                        optionLength++;\r
-                    }\r
-                    memcpy(optionResult + optionLength, buf, strlen((const char *) buf));\r
-                    optionLength += strlen((const char *) buf);\r
-                }\r
-            }\r
-            else\r
-            {\r
-                if (idx < count)\r
-                {\r
-                    uint32_t length = (uint32_t) strlen((const char *) buf);\r
-\r
-                    if (length <= CA_MAX_HEADER_OPTION_DATA_LENGTH)\r
-                    {\r
-                        outInfo->options[idx].optionID = opt_iter.type;\r
-                        outInfo->options[idx].optionLength = length;\r
-                        outInfo->options[idx].protocolID = CA_COAP_ID;\r
-                        memcpy(outInfo->options[idx].optionData, buf, length);\r
-                        idx++;\r
-                    }\r
-                }\r
-            }\r
-        }\r
-    }\r
-\r
-    // set token data\r
-    if (pdu->hdr->token_length > 0)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "inside pdu->hdr->token_length");\r
-        outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN + 1);\r
-        if (outInfo->token == NULL)\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");\r
-            OICFree(outInfo->options);\r
-            return;\r
-        }\r
-        memset(outInfo->token, 0, CA_MAX_TOKEN_LEN + 1);\r
-        memcpy(outInfo->token, pdu->hdr->token, CA_MAX_TOKEN_LEN);\r
-    }\r
-\r
-    // set payload data\r
-    if (NULL != pdu->data)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "inside pdu->data");\r
-        outInfo->payload = (char *) OICMalloc(strlen((const char *) pdu->data) + 1);\r
-        if (outInfo->payload == NULL)\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");\r
-            OICFree(outInfo->options);\r
-            OICFree(outInfo->token);\r
-            return;\r
-        }\r
-        memcpy(outInfo->payload, pdu->data, strlen((const char *) pdu->data) + 1);\r
-    }\r
-\r
-\r
-    memcpy(outUri, optionResult, strlen(optionResult));\r
-    OIC_LOG_V(DEBUG, TAG, "made URL : %s\n", optionResult);\r
-    OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo OUT");\r
-\r
-}\r
-\r
-CAResult_t CAGenerateTokenInternal(CAToken_t *token)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal IN");\r
-    if (token == NULL)\r
-    {\r
-        return CA_STATUS_FAILED;\r
-    }\r
-\r
-    // memory allocation\r
-    char *temp = (char *) OICMalloc(sizeof(char) * (CA_MAX_TOKEN_LEN + 1));\r
-    if (temp == NULL)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal, Memory allocation failed !");\r
-        return CA_MEMORY_ALLOC_FAILED;\r
-    }\r
-    memset(temp, 0, sizeof(char) * (CA_MAX_TOKEN_LEN + 1));\r
-\r
-    if (SEED == 0)\r
-    {\r
-        SEED = time(NULL);\r
-        if (SEED == -1)\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "Failed to Create Seed!");\r
-            SEED = 0;\r
-            OICFree(temp);\r
-            return CA_STATUS_FAILED;\r
-        }\r
-        srand(SEED);\r
-    }\r
-\r
-    // set random byte\r
-    uint32_t index;\r
-    for (index = 0; index < CA_MAX_TOKEN_LEN; index++)\r
-    {\r
-        // use valid characters\r
-        temp[index] = (rand() % 94 + 33) & 0xFF;\r
-    }\r
-\r
-    temp[index] = '\0';\r
-    // save token\r
-    *token = temp;\r
-\r
-    OIC_LOG_V(DEBUG, TAG, "generate the token(%s)!!", *token);\r
-    OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal OUT");\r
-    return CA_STATUS_OK;\r
-}\r
-\r
-void CADestroyTokenInternal(CAToken_t token)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal IN");\r
-    if (token != NULL)\r
-    {\r
-        OIC_LOG_V(DEBUG, TAG, "destroy the token(%s)!!", token);\r
-\r
-        OICFree(token);\r
-    }\r
-    OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal OUT");\r
-}\r
-\r
-void CADeinitialize(CAInfo_t *info)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CADeinitialize IN");\r
-\r
-    if (NULL != info)\r
-    {\r
-        if (NULL != info->options)\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "free options in CAInfo");\r
-            OICFree(info->options);\r
-        }\r
-\r
-        if (NULL != info->token)\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "free token in CAInfo");\r
-            OICFree(info->token);\r
-        }\r
-\r
-        if (NULL != info->payload)\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "free payload in CAInfo");\r
-            OICFree(info->payload);\r
-        }\r
-    }\r
-    OIC_LOG(DEBUG, TAG, "CADeinitialize OUT");\r
-}\r
-\r
-uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result,\r
-                         uint32_t buflen, uint32_t encode_always)\r
-{\r
-    const unsigned char hex[] = "0123456789ABCDEF";\r
-    uint32_t cnt = 0;\r
-    assert(data || len == 0);\r
-\r
-    if (buflen == 0 || len == 0)\r
-        return 0;\r
-\r
-    if (data == NULL)\r
-    {\r
-        return 0;\r
-    }\r
-\r
-    while (len)\r
-    {\r
-        if (!encode_always)\r
-        {\r
-            if (cnt == buflen)\r
-                break;\r
-            *result++ = *data;\r
-            ++cnt;\r
-        }\r
-        else\r
-        {\r
-            if (cnt + 4 < buflen)\r
-            {\r
-                *result++ = '\\';\r
-                *result++ = 'x';\r
-                *result++ = hex[(*data & 0xf0) >> 4];\r
-                *result++ = hex[*data & 0x0f];\r
-                cnt += 4;\r
-            }\r
-            else\r
-                break;\r
-        }\r
-\r
-        ++data;\r
-        --len;\r
-    }\r
-\r
-    *result = '\0';\r
-    return cnt;\r
-}\r
-\r
-CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)\r
-{\r
-    // pdu minimum size is 4 byte.\r
-    if (size < 4)\r
-        return CA_MSG_NONCONFIRM;\r
-\r
-    coap_hdr_t *hdr = (coap_hdr_t *) pdu;\r
-\r
-    return (CAMessageType_t) hdr->type;\r
-}\r
-\r
-uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)\r
-{\r
-    // pdu minimum size is 4 byte.\r
-    if (size < 4)\r
-        return 0;\r
-\r
-    coap_hdr_t *hdr = (coap_hdr_t *) pdu;\r
-\r
-    return ntohs(hdr->id);\r
-}\r
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "caprotocolmessage.h"
+#include "logger.h"
+#include "oic_malloc.h"
+
+#define TAG "CA"
+
+#define CA_FLAGS_BLOCK 0x01
+#define CA_BUFSIZE 128
+#define CA_COAP_MESSAGE_CON 0
+
+#define CA_RESPONSE_CLASS(C) (((C) >> 5)*100)
+#define CA_RESPONSE_CODE(C) (CA_RESPONSE_CLASS(C) + (C - COAP_RESPONSE_CODE(CA_RESPONSE_CLASS(C))))
+
+static int32_t SEED = 0;
+
+uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo, char *outUri)
+{
+    OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu IN");
+
+    if (NULL == pdu)
+        return 0;
+
+    uint32_t code = CA_NOT_FOUND;
+    CAGetRequestPDUInfo(pdu, &code, &(outReqInfo->info), outUri);
+    outReqInfo->method = code;
+    OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu OUT");
+    return 1;
+}
+
+uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo, char *outUri)
+{
+    OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu IN");
+    if (NULL == pdu)
+        return 0;
+
+    uint32_t code = CA_NOT_FOUND;
+    CAGetRequestPDUInfo(pdu, &code, &(outResInfo->info), outUri);
+    outResInfo->result = code;
+    OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu OUT");
+    return 1;
+}
+
+coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info)
+{
+    OIC_LOG(DEBUG, TAG, "CAGeneratePdu IN");
+
+    coap_pdu_t *pdu;
+    char *coapUri = NULL;
+    uint32_t coapHeaderLength = 12;
+    uint32_t length;
+    coap_list_t *optlist = NULL;
+
+    if (CA_EMPTY == code)
+    {
+        if (!(pdu = CACreatePDUforRSTandACK((code_t) code, info)))
+        {
+            return NULL;
+        }
+    }
+    else
+    {
+        if (NULL == uri)
+            return NULL;
+
+        length = strlen(uri);
+        if (CA_MAX_URI_LENGTH < length)
+        {
+            OIC_LOG(DEBUG, TAG, "check URI length..");
+            return NULL;
+        }
+
+        uint32_t uriLength = length + coapHeaderLength + 1;
+        coapUri = (char *) OICMalloc(uriLength);
+        if (NULL == coapUri)
+        {
+            OIC_LOG(DEBUG, TAG, "CAGeneratePdu, Memory allocation failed !");
+            return NULL;
+        }
+        memset(coapUri, 0, uriLength);
+
+        if (NULL != coapUri)
+        {
+            strcat(coapUri, "coap://[::]/");
+            strcat(coapUri, uri);
+
+            // parsing options in URI
+            CAParseURI(coapUri, &optlist);
+            OICFree(coapUri);
+            coapUri = NULL;
+
+            // parsing options in HeadOption
+            CAParseHeadOption(code, info, &optlist);
+        }
+
+        if (NULL != info.payload) // payload is include in request / response
+        {
+            if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload, info)))
+                return NULL;
+        }
+        else // payload is not include in request / response
+        {
+            if (!(pdu = CACreatePDUforRequest((code_t) code, optlist, info)))
+                return NULL;
+        }
+        // free option list
+        coap_delete_list(optlist);
+    }
+
+    // pdu print method : coap_show_pdu(pdu);
+    OIC_LOG(DEBUG, TAG, "CAGeneratePdu OUT");
+    return pdu;
+}
+
+coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode)
+{
+    OIC_LOG(DEBUG, TAG, "CAParsePDU IN");
+    coap_pdu_t *outpdu = coap_new_pdu();
+
+    coap_pdu_parse((unsigned char *) data, length, outpdu);
+    (*outCode) = (uint32_t) CA_RESPONSE_CODE(outpdu->hdr->code);
+    OIC_LOG(DEBUG, TAG, "CAParsePDU OUT");
+    return outpdu;
+}
+
+coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options,
+        const char *payload, const CAInfo_t info)
+{
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload IN");
+
+    coap_pdu_t *pdu;
+    coap_list_t *opt;
+
+    uint32_t CAFlags = 0;
+    coap_block_t
+    CABlock =
+    {   .num = 0, .m = 0, .szx = 6};
+
+    if (!(pdu = coap_new_pdu()))
+        return NULL;
+
+    unsigned short message_id;
+
+    if (info.messageId == 0)
+    {
+        /* initialize message id */
+        prng((unsigned char *) &message_id, sizeof(unsigned short));
+        ++message_id;
+
+        OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);
+    }
+    else
+    {
+        /* use saved message id */
+        message_id = info.messageId;
+    }
+
+    pdu->hdr->type = info.type;
+    pdu->hdr->id = htons(message_id);
+    pdu->hdr->code = COAP_RESPONSE_CODE(code);
+
+    if (info.token)
+    {
+        pdu->hdr->token_length = CA_MAX_TOKEN_LEN;
+        if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))
+        {
+            OIC_LOG(DEBUG, TAG, "cannot add token to request");
+        }
+    }
+    for (opt = options; opt; opt = opt->next)
+    {
+        OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
+                COAP_OPTION_DATA(*(coap_option *) opt->data));
+        coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+                COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+                COAP_OPTION_DATA(*(coap_option *) opt->data));
+    }
+
+    if (NULL != payload)
+    {
+        uint32_t len = strlen(payload);
+        if ((CAFlags & CA_FLAGS_BLOCK) == 0)
+        {
+            OIC_LOG_V(DEBUG, TAG, "coap_add_data, payload: %s", payload);
+            coap_add_data(pdu, len, (const unsigned char *) payload);
+        }
+        else
+        {
+            OIC_LOG_V(DEBUG, TAG, "coap_add_block, payload: %s", payload);
+            coap_add_block(pdu, len, (const unsigned char *) payload, CABlock.num, CABlock.szx);
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload OUT");
+    return pdu;
+}
+
+coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options, const CAInfo_t info)
+{
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest IN");
+
+    coap_pdu_t *pdu;
+    coap_list_t *opt;
+
+    if (!(pdu = coap_new_pdu()))
+    {
+        OIC_LOG(DEBUG, TAG, "Out of memory");
+        return NULL;
+    }
+
+    unsigned short message_id;
+
+    if (info.messageId == 0)
+    {
+        /* initialize message id */
+        prng((unsigned char *) &message_id, sizeof(unsigned short));
+        ++message_id;
+
+        OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);
+    }
+    else
+    {
+        /* use saved message id */
+        message_id = info.messageId;
+    }
+
+    pdu->hdr->type = info.type;
+    pdu->hdr->id = htons(message_id);
+    pdu->hdr->code = COAP_RESPONSE_CODE(code);
+
+    OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, strlen(info.token));
+    pdu->hdr->token_length = CA_MAX_TOKEN_LEN;
+
+    if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))
+    {
+        OIC_LOG(DEBUG, TAG, "cannot add token to request");
+    }
+
+    for (opt = options; opt; opt = opt->next)
+    {
+        coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+                COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+                COAP_OPTION_DATA(*(coap_option *) opt->data));
+    }
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest OUT");
+    return pdu;
+}
+
+coap_pdu_t *CACreatePDUforRSTandACK(const code_t code, const CAInfo_t info)
+{
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRSTandACK IN");
+
+    coap_pdu_t *pdu;
+
+    if (!(pdu = coap_new_pdu()))
+    {
+        OIC_LOG(DEBUG, TAG, "Out of memory");
+        return NULL;
+    }
+
+    unsigned short message_id;
+
+    if (info.messageId == 0)
+    {
+        /* initialize message id */
+        prng((unsigned char *) &message_id, sizeof(unsigned short));
+        ++message_id;
+
+        OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);
+    }
+    else
+    {
+        /* use saved message id */
+        message_id = info.messageId;
+    }
+
+    pdu->hdr->type = info.type;
+    pdu->hdr->id = htons(message_id);
+    pdu->hdr->code = COAP_RESPONSE_CODE(code);
+
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRSTandACK OUT");
+    return pdu;
+}
+
+void CAParseURI(const char *uriInfo, coap_list_t **optlist)
+{
+    OIC_LOG(DEBUG, TAG, "CAParseURI IN");
+
+    unsigned char portbuf[2];
+    unsigned char _buf[CA_BUFSIZE];
+    unsigned char *buf = _buf;
+    coap_uri_t uri;
+    size_t buflen;
+    uint32_t res;
+
+    OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
+
+    /* split arg into Uri-* options */
+    coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
+
+    if (uri.port != COAP_DEFAULT_PORT)
+    {
+        coap_insert(optlist,
+                CACreateNewOptionNode(COAP_OPTION_URI_PORT,
+                        coap_encode_var_bytes(portbuf, uri.port), portbuf), CAOrderOpts);
+    }
+
+    if (uri.path.length)
+    {
+        buflen = CA_BUFSIZE;
+        res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
+
+        while (res--)
+        {
+            coap_insert(optlist,
+                    CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf),
+                            COAP_OPT_VALUE(buf)), CAOrderOpts);
+            buf += COAP_OPT_SIZE(buf);
+        }
+    }
+
+    if (uri.query.length)
+    {
+        buflen = CA_BUFSIZE;
+        buf = _buf;
+        res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);
+
+        while (res--)
+        {
+            coap_insert(optlist,
+                    CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf),
+                            COAP_OPT_VALUE(buf)), CAOrderOpts);
+
+            buf += COAP_OPT_SIZE(buf);
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "CAParseURI OUT");
+}
+
+void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist)
+{
+    OIC_LOG(DEBUG, TAG, "CAParseHeadOption IN");
+    OIC_LOG_V(DEBUG, TAG, "start parse Head Option : %d", info.numOptions);
+
+    uint32_t i;
+    for (i = 0; i < info.numOptions; i++)
+    {
+        uint32_t id = info.options[i].optionID;
+        if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)
+        {
+            OIC_LOG_V(DEBUG, TAG, "it is not Header Option : %d", id);
+        }
+        else
+        {
+            if (info.options[i].optionData && info.options[i].optionLength > 0)
+            {
+                OIC_LOG_V(DEBUG, TAG, "Head Option ID: %d", id);
+                OIC_LOG_V(DEBUG, TAG, "Head Option data: %s", info.options[i].optionData);
+                OIC_LOG_V(DEBUG, TAG, "Head Option length: %d", info.options[i].optionLength);
+                coap_insert(optlist,
+                        CACreateNewOptionNode(id, info.options[i].optionLength,
+                                info.options[i].optionData), CAOrderOpts);
+            }
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "CAParseHeadOption OUT");
+}
+
+coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length, const uint8_t *data)
+{
+    OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode IN");
+    coap_option *option;
+    coap_list_t *node;
+
+    option = coap_malloc(sizeof(coap_option) + length + 1);
+    if (!option)
+    {
+        OIC_LOG(DEBUG, TAG, "Out of memory");
+        return NULL;
+    }
+    memset(option, 0, sizeof(coap_option) + length + 1);
+
+    COAP_OPTION_KEY(*option) = key;
+    COAP_OPTION_LENGTH(*option) = length;
+    memcpy(COAP_OPTION_DATA(*option), data, length);
+
+    /* we can pass NULL here as delete function since option is released automatically  */
+    node = coap_new_listnode(option, NULL);
+
+    if (!node)
+    {
+        OIC_LOG(DEBUG, TAG, "coap_new_listnode returns NULL");
+        coap_free(option);
+        return NULL;
+    }
+    //coap_free(option);
+    OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode OUT");
+    return node;
+}
+
+int CAOrderOpts(void *a, void *b)
+{
+    OIC_LOG(DEBUG, TAG, "CAOrderOpts IN");
+    if (!a || !b)
+    {
+        return a < b ? -1 : 1;
+    }
+
+    if (COAP_OPTION_KEY(*(coap_option *) a) < COAP_OPTION_KEY(*(coap_option *) b))
+    {
+        return -1;
+    }
+    OIC_LOG(DEBUG, TAG, "CAOrderOpts OUT");
+    return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option *) b);
+}
+
+uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
+{
+    OIC_LOG(DEBUG, TAG, "CAGetOptionCount IN");
+    uint32_t count = 0;
+    coap_opt_t *option;
+
+    while ((option = coap_option_next(&opt_iter)))
+    {
+        if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
+        {
+
+        }
+        else
+        {
+            count++;
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "CAGetOptionCount OUT");
+    return count;
+}
+
+void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo, char *outUri)
+{
+    OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo IN");
+    char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */
+    uint32_t encode = 0;
+    coap_opt_iterator_t opt_iter;
+    coap_opt_t *option;
+    char optionResult[CA_MAX_URI_LENGTH] =
+    { 0, };
+    uint32_t count = 0, idx = 0;
+    uint32_t optionLength = 0;
+    uint32_t isfirstsetflag = 0;
+
+    coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL);
+
+    memset(optionResult, 0, sizeof(optionResult));
+
+    // set code
+    (*outCode) = (uint32_t) CA_RESPONSE_CODE(pdu->hdr->code);
+
+    // init HeaderOption list
+    count = CAGetOptionCount(opt_iter);
+
+    memset(outInfo, 0, sizeof(CAInfo_t));
+    outInfo->numOptions = count;
+    // set type
+    outInfo->type = pdu->hdr->type;
+
+    // set message id
+    outInfo->messageId = ntohs(pdu->hdr->id);
+
+    if (count > 0)
+    {
+        outInfo->options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * count);
+        if (outInfo->options == NULL)
+        {
+            OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");
+            return;
+        }
+        memset(outInfo->options, 0, sizeof(CAHeaderOption_t) * count);
+    }
+
+    while ((option = coap_option_next(&opt_iter)))
+    {
+
+        if (CAGetOptionData((uint8_t *) (COAP_OPT_VALUE(option)), COAP_OPT_LENGTH(option),
+                (uint8_t *) buf, sizeof(buf), encode))
+        {
+            OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
+            if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
+            {
+                if (0 == isfirstsetflag)
+                {
+                    isfirstsetflag = 1;
+                    memcpy(optionResult + optionLength, "/", 1);
+                    optionLength++;
+                    memcpy(optionResult + optionLength, buf, strlen((const char *) buf));
+                    optionLength += strlen((const char *) buf);
+                }
+                else
+                {
+                    if (COAP_OPTION_URI_PATH == opt_iter.type)
+                    {
+                        memcpy(optionResult + optionLength, "/", 1);
+                        optionLength++;
+                    }
+                    else if (COAP_OPTION_URI_QUERY == opt_iter.type)
+                    {
+                        memcpy(optionResult + optionLength, "?", 1);
+                        optionLength++;
+                    }
+                    memcpy(optionResult + optionLength, buf, strlen((const char *) buf));
+                    optionLength += strlen((const char *) buf);
+                }
+            }
+            else
+            {
+                if (idx < count)
+                {
+                    uint32_t length = (uint32_t) strlen((const char *) buf);
+
+                    if (length <= CA_MAX_HEADER_OPTION_DATA_LENGTH)
+                    {
+                        outInfo->options[idx].optionID = opt_iter.type;
+                        outInfo->options[idx].optionLength = length;
+                        outInfo->options[idx].protocolID = CA_COAP_ID;
+                        memcpy(outInfo->options[idx].optionData, buf, length);
+                        idx++;
+                    }
+                }
+            }
+        }
+    }
+
+    // set token data
+    if (pdu->hdr->token_length > 0)
+    {
+        OIC_LOG(DEBUG, TAG, "inside pdu->hdr->token_length");
+        outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN + 1);
+        if (outInfo->token == NULL)
+        {
+            OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");
+            OICFree(outInfo->options);
+            return;
+        }
+        memset(outInfo->token, 0, CA_MAX_TOKEN_LEN + 1);
+        memcpy(outInfo->token, pdu->hdr->token, CA_MAX_TOKEN_LEN);
+    }
+
+    // set payload data
+    if (NULL != pdu->data)
+    {
+        OIC_LOG(DEBUG, TAG, "inside pdu->data");
+        outInfo->payload = (char *) OICMalloc(strlen((const char *) pdu->data) + 1);
+        if (outInfo->payload == NULL)
+        {
+            OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");
+            OICFree(outInfo->options);
+            OICFree(outInfo->token);
+            return;
+        }
+        memcpy(outInfo->payload, pdu->data, strlen((const char *) pdu->data) + 1);
+    }
+
+    memcpy(outUri, optionResult, strlen(optionResult));
+    OIC_LOG_V(DEBUG, TAG, "made URL : %s\n", optionResult);
+    OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo OUT");
+
+}
+
+CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CAGetTokenFromPDU");
+    if (NULL == pdu_hdr)
+    {
+        OIC_LOG(DEBUG, TAG, "pdu_hdr is null");
+        return CA_STATUS_FAILED;
+    }
+    // set token data
+    if (pdu_hdr->token_length > 0)
+    {
+        OIC_LOG(DEBUG, TAG, "inside pdu_hdr->token_length");
+        outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN + 1);
+        if (outInfo->token == NULL)
+        {
+            OIC_LOG(DEBUG, TAG, "CAGetTokenFromPDU, Memory allocation failed !");
+            return CA_STATUS_FAILED;
+        }
+        memset(outInfo->token, 0, CA_MAX_TOKEN_LEN + 1);
+        memcpy(outInfo->token, pdu_hdr->token, CA_MAX_TOKEN_LEN);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT - CAGetTokenFromPDU");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGenerateTokenInternal(CAToken_t *token)
+{
+    OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal IN");
+    if (token == NULL)
+    {
+        return CA_STATUS_FAILED;
+    }
+
+    // memory allocation
+    char *temp = (char *) OICMalloc(sizeof(char) * (CA_MAX_TOKEN_LEN + 1));
+    if (temp == NULL)
+    {
+        OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal, Memory allocation failed !");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    memset(temp, 0, sizeof(char) * (CA_MAX_TOKEN_LEN + 1));
+
+    if (SEED == 0)
+    {
+        SEED = time(NULL);
+        if (SEED == -1)
+        {
+            OIC_LOG(DEBUG, TAG, "Failed to Create Seed!");
+            SEED = 0;
+            OICFree(temp);
+            return CA_STATUS_FAILED;
+        }
+        srand(SEED);
+    }
+
+    // set random byte
+    uint32_t index;
+    for (index = 0; index < CA_MAX_TOKEN_LEN; index++)
+    {
+        // use valid characters
+        temp[index] = (rand() % 94 + 33) & 0xFF;
+    }
+
+    temp[index] = '\0';
+    // save token
+    *token = temp;
+
+    OIC_LOG_V(DEBUG, TAG, "generate the token(%s)!!", *token);
+    OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal OUT");
+    return CA_STATUS_OK;
+}
+
+void CADestroyTokenInternal(CAToken_t token)
+{
+    OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal IN");
+    if (token != NULL)
+    {
+        OIC_LOG_V(DEBUG, TAG, "destroy the token(%s)!!", token);
+
+        OICFree(token);
+    }
+    OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal OUT");
+}
+
+void CADeinitialize(CAInfo_t *info)
+{
+    OIC_LOG(DEBUG, TAG, "CADeinitialize IN");
+
+    if (NULL != info)
+    {
+        if (NULL != info->options)
+        {
+            OIC_LOG(DEBUG, TAG, "free options in CAInfo");
+            OICFree(info->options);
+        }
+
+        if (NULL != info->token)
+        {
+            OIC_LOG(DEBUG, TAG, "free token in CAInfo");
+            OICFree(info->token);
+        }
+
+        if (NULL != info->payload)
+        {
+            OIC_LOG(DEBUG, TAG, "free payload in CAInfo");
+            OICFree(info->payload);
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "CADeinitialize OUT");
+}
+
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result, uint32_t buflen,
+        uint32_t encode_always)
+{
+    const unsigned char hex[] = "0123456789ABCDEF";
+    uint32_t cnt = 0;
+    assert(data || len == 0);
+
+    if (buflen == 0 || len == 0)
+        return 0;
+
+    if (data == NULL)
+    {
+        return 0;
+    }
+
+    while (len)
+    {
+        if (!encode_always)
+        {
+            if (cnt == buflen)
+                break;
+            *result++ = *data;
+            ++cnt;
+        }
+        else
+        {
+            if (cnt + 4 < buflen)
+            {
+                *result++ = '\\';
+                *result++ = 'x';
+                *result++ = hex[(*data & 0xf0) >> 4];
+                *result++ = hex[*data & 0x0f];
+                cnt += 4;
+            }
+            else
+                break;
+        }
+
+        ++data;
+        --len;
+    }
+
+    *result = '\0';
+    return cnt;
+}
+
+CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
+{
+    // pdu minimum size is 4 byte.
+    if (size < 4)
+        return CA_MSG_NONCONFIRM;
+
+    coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+    return (CAMessageType_t) hdr->type;
+}
+
+uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
+{
+    // pdu minimum size is 4 byte.
+    if (size < 4)
+        return 0;
+
+    coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+    return ntohs(hdr->id);
+}
+
+CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
+{
+    // pdu minimum size is 4 byte.
+    if (size < 4)
+        return 0;
+
+    coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+    return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->code);
+}
index 5e29c08..c011eae 100644 (file)
@@ -33,6 +33,8 @@
 #define CA_BUFSIZE 128
 #define CA_COAP_MESSAGE_CON 0
 
+#define CA_RESPONSE_CLASS(C) (((C) >> 5)*100)
+#define CA_RESPONSE_CODE(C) (CA_RESPONSE_CLASS(C) + (C - COAP_RESPONSE_CODE(CA_RESPONSE_CLASS(C))))
 
 uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,
                                  char *outUri)
@@ -73,47 +75,60 @@ coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t i
     uint32_t length;
     coap_list_t *optlist = NULL;
 
-    if (NULL == uri)
-        return NULL;
-
-    length = strlen(uri);
-    if (CA_MAX_URI_LENGTH < length)
+    if(CA_EMPTY == code)
     {
-        OIC_LOG(DEBUG, TAG, "URI len err");
-        return NULL;
+        if (!(pdu = CACreatePDUforRSTandACK((code_t) code, info)))
+        {
+            return NULL;
+        }
     }
-
-    coapUri = (char *) OICMalloc(length + coapHeaderLength + 1);
-    if (coapUri == NULL)
+    else
     {
-        OIC_LOG(ERROR, TAG, "error");
-        return NULL;
-    }
-    memset(coapUri, 0, length + coapHeaderLength + 1);
+        if (NULL == uri)
+            return NULL;
 
-    if (NULL != coapUri)
-    {
-        memcpy(coapUri, "coap://[::]/", coapHeaderLength);
-        memcpy(coapUri + coapHeaderLength, uri, length);
+        length = strlen(uri);
+        if (CA_MAX_URI_LENGTH < length)
+        {
+            OIC_LOG(DEBUG, TAG, "URI len err");
+            return NULL;
+        }
 
-        // parsing options in URI
-        CAParseURI(coapUri, &optlist);
+        uint32_t uriLength = length + coapHeaderLength + 1;
+        coapUri = (char *) OICMalloc(uriLength);
+        if (NULL == coapUri)
+        {
+            OIC_LOG(ERROR, TAG, "error");
+            return NULL;
+        }
+        memset(coapUri, 0, uriLength);
 
-        // parsing options in HeadOption
-        CAParseHeadOption(code, info, &optlist);
+        if (NULL != coapUri)
+        {
+            memcpy(coapUri, "coap://[::]/", coapHeaderLength);
+            memcpy(coapUri + coapHeaderLength, uri, length);
 
-        OICFree(coapUri);
-    }
+            // parsing options in URI
+            CAParseURI(coapUri, &optlist);
+            OICFree(coapUri);
+            coapUri = NULL;
 
-    if (NULL != info.payload) // payload is include in request / response
-    {
-        if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload, info)))
-            return NULL;
-    }
-    else // payload is not include in request / response
-    {
-        if (!(pdu = CACreatePDUforRequest((code_t) code, optlist, info)))
-            return NULL;
+            // parsing options in HeadOption
+            CAParseHeadOption(code, info, &optlist);
+        }
+
+        if (NULL != info.payload) // payload is include in request / response
+        {
+            if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload, info)))
+                return NULL;
+        }
+        else // payload is not include in request / response
+        {
+            if (!(pdu = CACreatePDUforRequest((code_t) code, optlist, info)))
+                return NULL;
+        }
+        // free option list
+        coap_delete_list(optlist);
     }
 
     // pdu print method : coap_show_pdu(pdu);
@@ -127,7 +142,7 @@ coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode)
     coap_pdu_t *outpdu = coap_new_pdu();
 
     coap_pdu_parse((unsigned char *) data, length, outpdu);
-    (*outCode) = (uint32_t) outpdu->hdr->code;
+    (*outCode) = (uint32_t) CA_RESPONSE_CODE(outpdu->hdr->code);
     OIC_LOG(DEBUG, TAG, "OUT");
     return outpdu;
 }
@@ -165,7 +180,7 @@ coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *opt
 
     pdu->hdr->type = info.type;
     pdu->hdr->id = htons(message_id);
-    pdu->hdr->code = code;
+    pdu->hdr->code = COAP_RESPONSE_CODE(code);
 
     if (info.token)
     {
@@ -230,7 +245,7 @@ coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,
 
     pdu->hdr->type = info.type;
     pdu->hdr->id = htons(message_id);
-    pdu->hdr->code = code;
+    pdu->hdr->code = COAP_RESPONSE_CODE(code);
 
     OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, strlen(info.token));
     pdu->hdr->token_length = CA_MAX_TOKEN_LEN;
@@ -250,6 +265,42 @@ coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,
     return pdu;
 }
 
+coap_pdu_t *CACreatePDUforRSTandACK(const code_t code, const CAInfo_t info)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    coap_pdu_t *pdu;
+
+    if (!(pdu = coap_new_pdu()))
+    {
+        OIC_LOG(DEBUG, TAG, "error");
+        return NULL;
+    }
+
+    unsigned short message_id;
+
+    if (info.messageId == 0)
+    {
+        /* initialize message id */
+        prng((unsigned char * )&message_id, sizeof(unsigned short));
+        ++message_id;
+
+        OIC_LOG_V(DEBUG, TAG, "msg id(%d)", message_id);
+    }
+    else
+    {
+        /* use saved message id */
+        message_id = info.messageId;
+    }
+
+    pdu->hdr->type = info.type;
+    pdu->hdr->id = htons(message_id);
+    pdu->hdr->code = COAP_RESPONSE_CODE(code);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return pdu;
+}
+
 void CAParseURI(const char *uriInfo, coap_list_t **optlist)
 {
     OIC_LOG(DEBUG, TAG, "IN");
@@ -362,7 +413,7 @@ coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length,
         coap_free(option);
         return NULL;
     }
-   
+
     OIC_LOG(DEBUG, TAG, "OUT");
     return node;
 }
@@ -423,7 +474,7 @@ void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *out
     memset(optionResult, 0, sizeof(optionResult));
 
     // set code
-    (*outCode) = (uint32_t) pdu->hdr->code;
+    (*outCode) = (uint32_t) CA_RESPONSE_CODE(pdu->hdr->code);
 
     // init HeaderOption list
     count = CAGetOptionCount(opt_iter);
@@ -537,6 +588,32 @@ void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *out
 
 }
 
+CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if(NULL == pdu_hdr)
+    {
+        OIC_LOG(DEBUG, TAG, "error");
+        return CA_STATUS_FAILED;
+    }
+    // set token data
+    if (pdu_hdr->token_length > 0)
+    {
+        OIC_LOG(DEBUG, TAG, "toklen > 0");
+        outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN + 1);
+        if (outInfo->token == NULL)
+        {
+            OIC_LOG(DEBUG, TAG, "error");
+            return CA_STATUS_FAILED;
+        }
+        memset(outInfo->token, 0, CA_MAX_TOKEN_LEN + 1);
+        memcpy(outInfo->token, pdu_hdr->token, CA_MAX_TOKEN_LEN);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT - CAGetTokenFromPDU");
+
+    return CA_STATUS_OK;
+}
+
 CAResult_t CAGenerateTokenInternal(CAToken_t *token)
 {
     OIC_LOG(DEBUG, TAG, "IN");
@@ -673,3 +750,14 @@ uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
 
     return ntohs(hdr->id);
 }
+
+CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
+{
+    // pdu minimum size is 4 byte.
+    if (size < 4)
+        return 0;
+
+    coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+    return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->code);
+}
index ca302ee..e6a8dae 100644 (file)
 #ifdef __ANDROID__
 #include <linux/time.h>
 #endif
-
+#include "coap.h"
 #include "caretransmission.h"
 #include "caremotehandler.h"
 #include "caprotocolmessage.h"
 #include "oic_malloc.h"
 #include "logger.h"
 
-#define TAG PCF("RET")
+#define TAG PCF("CA")
 
 typedef struct
 {
@@ -384,8 +384,11 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context,
 }
 
 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
-                                        const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
+                                        const CARemoteEndpoint_t *endpoint,
+                                        const void *pdu, uint32_t size,
+                                        void **retransmissionPdu)
 {
+    OIC_LOG_V(DEBUG, TAG, "IN - CARetransmissionReceivedData");
     if (context == NULL || endpoint == NULL || pdu == NULL)
     {
         OIC_LOG_V(DEBUG, TAG, "invalid parameter..");
@@ -429,7 +432,32 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
         // found index
         if ((retData->endpoint->connectivityType == endpoint->connectivityType)
             && retData->messageId == messageId)
+        {
+            // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
+            // if retransmission was finish..token will be unavailable.
+            if(CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
+            {
+                OIC_LOG_V(DEBUG, TAG, "code is CA_EMPTY..");
+
+                if(NULL == retData->pdu)
+                {
+                    OIC_LOG_V(DEBUG, TAG, "retData->pdu is null");
+                }
+
+                // copy PDU data
+                (*retransmissionPdu) = (void *) OICMalloc(sizeof(int8_t) * retData->size);
+                if ((*retransmissionPdu) == NULL)
+                {
+                    OICFree(retData);
+                    OIC_LOG_V(DEBUG, TAG, "memory error!!");
+                    return CA_MEMORY_ALLOC_FAILED;
+                }
+                memset((*retransmissionPdu), 0, sizeof(int8_t) * retData->size);
+                memcpy((*retransmissionPdu), retData->pdu, sizeof(int8_t) * retData->size);
+            }
+
             break;
+        }
     }
 
     // #2. remove data from list
@@ -451,6 +479,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
     // mutex unlock
     u_mutex_unlock(context->threadMutex);
 
+    OIC_LOG_V(DEBUG, TAG, "OUT - CARetransmissionReceivedData");
     return CA_STATUS_OK;
 }
 
index 776e9be..c2c1f81 100644 (file)
@@ -18,7 +18,7 @@
  *
  ******************************************************************/
 #include "caretransmission_singlethread.h"
-
+#include "coap.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -287,7 +287,9 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context,
 }
 
 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
-                                        const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
+                                        const CARemoteEndpoint_t *endpoint,
+                                        const void *pdu, uint32_t size,
+                                        void **retransmissionPdu)
 {
     OIC_LOG(DEBUG, TAG, "IN");
     if (context == NULL || endpoint == NULL || pdu == NULL)
@@ -330,7 +332,32 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
         // found index
         if ((retData->endpoint->connectivityType == endpoint->connectivityType)
             && retData->messageId == messageId)
+        {
+            // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
+            // if retransmission was finish..token will be unavailable.
+            if(CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
+            {
+                OIC_LOG(DEBUG, TAG, "CA_EMPTY");
+
+                if(NULL == retData->pdu)
+                {
+                    OIC_LOG(DEBUG, TAG, "retData->pdu is null");
+                }
+
+                // copy PDU data
+                (*retransmissionPdu) = (void *) OICMalloc(sizeof(int8_t) * retData->size);
+                if (NULL == (*retransmissionPdu))
+                {
+                    OICFree(retData);
+                    OIC_LOG(DEBUG, TAG, "error");
+                    return CA_MEMORY_ALLOC_FAILED;
+                }
+                memset((*retransmissionPdu), 0, sizeof(int8_t) * retData->size);
+                memcpy((*retransmissionPdu), retData->pdu, sizeof(int8_t) * retData->size);
+            }
+
             break;
+        }
     }
 
     // #2. remove data from list