IP address plumbing changes to support IPv6
[platform/upstream/iotivity.git] / resource / csdk / connectivity / samples / tizen / casample.c
index 616383d..14cbccc 100644 (file)
  *
  ******************************************************************/
 
-#include <ctype.h>
-#include <fcntl.h>
-#include <errno.h>
 #include <glib.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <unistd.h>
 #include <string.h>
+#include <unistd.h>
+#include <stdbool.h>
 #include <pthread.h>
 #include "cacommon.h"
 #include "cainterface.h"
 
-static GMainLoop *mainloop;
-
-pthread_t thread;
-
+#ifdef __WITH_DTLS__
+#include "ocsecurityconfig.h"
+#endif
+/**
+ * @def MAX_BUF_LEN
+ * @brief maximum buffer length
+ */
 #define MAX_BUF_LEN 1024
+
+/**
+ * @def MAX_OPT_LEN
+ * @brief maximum option length
+ */
 #define MAX_OPT_LEN 16
-#define TRUE 1
-#define FALSE 0
+
+/**
+ * @def PORT_LENGTH
+ * @brief maximum port length
+ */
+#define PORT_LENGTH 5
+
+/**
+ * @def SECURE_DEFAULT_PORT
+ * @brief default secured port
+ */
+#define SECURE_DEFAULT_PORT 5684
+
+#define RESOURCE_URI_LENGTH 14
 
 /**
  * @def RS_IDENTITY
@@ -49,25 +67,24 @@ pthread_t thread;
  */
 #define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
 
+static GMainLoop *g_mainloop = NULL;
+pthread_t thread;
 
-int gReceived;
-CABool_t gLocalUnicastPort;
-CABool_t gLocalSecurePort;
-CAConnectivityType_t gSelectedNwType = CA_ETHERNET;
-const char* gMessageType[] = {"CON", "NON", "ACK", "RESET"};
+int g_received;
+uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
+CATransportType_t g_selected_nw_type = CA_IPV4;
+const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
 
 char get_menu();
 void process();
 CAResult_t get_network_type();
+CAResult_t get_input_data(char *buf, int32_t length);
 
-CAResult_t initialize();
 void start_listening_server();
 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();
 void unselect_network();
@@ -77,119 +94,183 @@ void get_network_info();
 
 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token);
+void error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
+
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
 void get_resource_uri(char *URI, char *resourceURI, int length);
 int get_secure_information(CAPayload_t payLoad);
 
-static CAToken_t gLastRequestToken = NULL;
-static const char *gSecureInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-                                     "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
-static const char *gNormalInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
-                                     "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
+static CAToken_t g_last_request_token = NULL;
+static const char SECURE_COAPS_PREFIX[] = "coaps://";
+static const char SECURE_INFO_DATA[] =
+    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+    "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+static const char NORMAL_INFO_DATA[] =
+    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+    "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
 
 #ifdef __WITH_DTLS__
-static OCDtlsPskCredsBlob *pskCredsBlob = NULL;
+static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
+
 void clearDtlsCredentialInfo()
 {
     printf("clearDtlsCredentialInfo IN\n");
     if (pskCredsBlob)
     {
         // Initialize sensitive data to zeroes before freeing.
-        memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
-        free(pskCredsBlob->creds);
+        if (pskCredsBlob->creds)
+        {
+            memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+            free(pskCredsBlob->creds);
+        }
 
-        memset(pskCredsBlob, 0, sizeof(OCDtlsPskCredsBlob));
+        memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
         free(pskCredsBlob);
         pskCredsBlob = NULL;
     }
     printf("clearDtlsCredentialInfo OUT\n");
 }
 
-// Internal API. Invoked by OC stack to retrieve credentials from this module
-void CAGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo)
+// Internal API. Invoked by CA stack to retrieve credentials from this module.
+void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
 {
     printf("CAGetDtlsPskCredentials IN\n");
 
-    *credInfo = pskCredsBlob;
+    if(NULL == credInfo)
+    {
+        printf("Invalid credential container");
+        return;
+    }
+
+    *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+    if (NULL == *credInfo)
+    {
+        printf("Failed to allocate credential blob.");
+        return;
+    }
+
+    int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
+    (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
+    if (NULL == (*credInfo)->creds)
+    {
+        printf("Failed to allocate credentials.");
+        free(*credInfo);
+        *credInfo = NULL;
+        return;
+    }
+
+    memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
+    (*credInfo)->num = pskCredsBlob->num;
+    memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
 
     printf("CAGetDtlsPskCredentials OUT\n");
 }
 
-int32_t SetCredentials()
+CAResult_t SetCredentials()
 {
     printf("SetCredentials IN\n");
-    pskCredsBlob = (OCDtlsPskCredsBlob *)malloc(sizeof(OCDtlsPskCredsBlob));
-
-    memset(pskCredsBlob, 0x0, sizeof(OCDtlsPskCredsBlob));
+    pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+    if (NULL == pskCredsBlob)
+    {
+        printf("Memory allocation failed!\n");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
     memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
 
     pskCredsBlob->num = 1;
 
     pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+    if (NULL == pskCredsBlob->creds)
+    {
+        printf("Memory allocation failed!\n");
+        free(pskCredsBlob);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
 
     memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
     memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
 
     printf("SetCredentials OUT\n");
-    return 1;
+    return CA_STATUS_OK;
 }
 #endif
-void pthread_func()
+
+void GMainLoopThread()
+{
+    g_main_loop_run(g_mainloop);
+}
+
+CAResult_t Initialize()
 {
-    g_main_loop_run(mainloop);
+    g_mainloop = g_main_loop_new(NULL, FALSE);
+    if(!g_mainloop)
+    {
+        printf("g_main_loop_new failed\n");
+        return CA_STATUS_FAILED;
+    }
+
+    int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
+    if (result < 0)
+    {
+        printf("pthread_create failed in initialize\n");
+        return CA_STATUS_FAILED;
+    }
+
+    CAResult_t res = CAInitialize();
+    if (res != CA_STATUS_OK)
+    {
+        printf("CAInitialize fail\n");
+    }
+    return res;
 }
 
 int main()
 {
-    system("clear");
+    int ret = system("clear");
+    // shell invoke error: 127, others: -1
+    if (127 == ret || -1 == ret)
+    {
+        printf("Terminal Clear Error: %d\n", ret);
+    }
 
-    printf("\n=============================================\n");
+    printf("=============================================\n");
     printf("\t\tsample main\n");
     printf("=============================================\n");
 
-    CAResult_t res;
+    CAResult_t res = Initialize();
+    if (CA_STATUS_OK != res)
+    {
+        printf("Initialization is  failed\n");
+        return -1;
+    }
+
     /*
-    * Read DTLS PSK credentials from persistent storage and
-    * set in the OC stack.
-    */
+     * Read DTLS PSK credentials from persistent storage and
+     * set in the OC stack.
+     */
 #ifdef __WITH_DTLS__
-    if (SetCredentials() == 0)
+    res = SetCredentials();
+    if (CA_STATUS_OK != res)
     {
         printf("SetCredentials failed\n");
-        return 0;
+        return -1;
     }
 
     res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
-    if(res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
         printf("Set credential handler fail\n");
-        return 0;
-    }
-#endif
-    res = initialize();
-    if (res != CA_STATUS_OK)
-    {
-        printf("CAInitialize fail\n");
-        return 0;
-    }
-
-#if 0
-    // network enable
-    // default
-    printf("select default network(WIFI)\n");
-    res = CASelectNetwork(CA_WIFI);
-    if (res != CA_STATUS_OK)
-    {
-        printf("CASelectNetwork fail\n");
-        return 0;
+        return -1;
     }
 #endif
 
     // set handler.
-    CARegisterHandler(request_handler, response_handler);
+    CARegisterHandler(request_handler, response_handler, error_handler);
 
     process();
 
+    CADestroyToken(g_last_request_token);
+
     CATerminate();
 #ifdef __WITH_DTLS__
     clearDtlsCredentialInfo();
@@ -201,20 +282,21 @@ void process()
 {
     while (1)
     {
-        char menu = toupper(get_menu());
+        char menu = get_menu();
 
         switch (menu)
         {
             case 'm': // menu
             case 'M':
-                continue;
-            case 'Q': // quits the sample program
+                break;
+
+            case 'q': // quit
+            case 'Q':
                 printf("quit..!!\n");
-                g_main_loop_quit(mainloop);
                 return;
 
             case 's': // start server
-            case 'S': // start server
+            case 'S':
                 start_listening_server();
                 break;
 
@@ -224,44 +306,47 @@ void process()
                 break;
 
             case 'c': // start client
-            case 'D':
+            case 'C':
                 start_discovery_server();
                 break;
 
-            case 'F': // find resource
+            case 'f': // find resource
+            case 'F':
                 find_resource();
                 break;
 
-            case 'R': // send request
+            case 'r': // send request
+            case 'R':
                 send_request();
                 break;
 
-            case 'A': // advertise resource
-                advertise_resource();
-                break;
-
             case 'b': // send notification
             case 'B':
                 send_notification();
                 break;
-            case 'N': // select network
+
+            case 'n': // select network
+            case 'N':
                 select_network();
                 break;
 
-            case 'X': // unselect network
+            case 'x': // unselect network
+            case 'X':
                 unselect_network();
                 break;
 
-            case 'H': // handle request response
+            case 'h': // handle request response
+            case 'H':
                 handle_request_response();
                 break;
+
             case 'y':
             case 'Y':
                 while (1)
                 {
-                    gReceived = 0;
+                    g_received = 0;
                     find_fixed_resource();
-                    while (gReceived == 0)
+                    while (g_received == 0)
                     {
                         sleep(1);
                         handle_request_response();
@@ -269,6 +354,19 @@ void process()
                     }
                 }
                 break;
+
+            case 'w':
+            case 'W':
+                g_received = 0;
+                start_discovery_server();
+                //send_secure_request();
+                while (g_received == 0)
+                {
+                    sleep(1);
+                    handle_request_response();
+                }
+                break;
+
             case 'z':
             case 'Z':
                 start_listening_server();
@@ -285,469 +383,466 @@ void process()
                 break;
 
             default:
-                printf("not supported menu!!\n");
+                printf("Not supported menu!!\n");
                 break;
         }
     }
 
 }
 
-CAResult_t initialize()
-{
-    mainloop = g_main_loop_new(NULL, FALSE);
-    pthread_create (&thread, NULL, (void *) &pthread_func, NULL);
-
-    CAResult_t res = CAInitialize();
-    if (res != CA_STATUS_OK)
-    {
-        printf("CAInitialize fail\n");
-        return CA_STATUS_FAILED;
-    }
-
-    return CA_STATUS_OK;
-}
-
 void start_listening_server()
 {
-    printf("start listening server!!\n");
+    printf("Start listening server!!\n");
 
     CAResult_t res = CAStartListeningServer();
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("start listening server fail\n");
+        printf("Start listening server fail, error code : %d\n", res);
     }
     else
     {
-        printf("start listening server success\n");
+        printf("Start listening server success\n");
     }
 }
 
 void start_discovery_server()
 {
-    printf("start discovery client!!\n");
+    printf("Start discovery client!!\n");
 
     CAResult_t res = CAStartDiscoveryServer();
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("start discovery client fail\n");
+        printf("Start discovery client fail, error code : %d\n", res);
     }
     else
     {
-        printf("start discovery client success\n");
+        printf("Start discovery client success\n");
     }
 }
 
 void find_fixed_resource()
 {
-    char buf[MAX_BUF_LEN] =
-    { 0, };
-    strcpy(buf, "/a/light");
-
     // create token
     CAToken_t token = NULL;
-    CAResult_t res = CAGenerateToken(&token);
-    if (res != CA_STATUS_OK)
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!");
-        token = NULL;
+        printf("Token generate error!!");
+        return;
     }
 
-    printf("generated token %s\n", (token != NULL) ? token : "");
+    printf("Generated token %s\n", token);
 
-    res = CAFindResource(buf, token);
-    if (res != CA_STATUS_OK)
+    char buf[MAX_BUF_LEN] = { 0 };
+    strcpy(buf, "/a/light");
+
+    res = CAFindResource(buf, token, tokenLength);
+    if (CA_STATUS_OK != res)
     {
-        printf("find resource error!!\n");
+        printf("Find resource error : %d\n", res);
     }
     else
     {
-        printf("find resource to %s URI\n", buf);
+        printf("Find resource to %s URI\n", buf);
     }
 
     // delete token
-    /*
-     if (token != NULL)
-     {
-     CADestroyToken(token);
-     }
-     */
+    CADestroyToken(token);
 
     printf("=============================================\n");
 }
+
 void find_resource()
 {
-    char buf[MAX_BUF_LEN];
-
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
     printf("\n=============================================\n");
     printf("ex) /a/light\n");
     printf("reference uri : ");
 
-    gets(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
 
     // create token
     CAToken_t token = NULL;
-    CAResult_t res = CAGenerateToken(&token);
-    if (res != CA_STATUS_OK)
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!\n");
-        token = NULL;
+        printf("Token generate error!!\n");
+        return;
     }
 
-    printf("generated token %s\n", (token != NULL) ? token : "");
+    printf("Generated token %s\n", token);
 
-    res = CAFindResource(buf, token);
-    if (res != CA_STATUS_OK)
+    res = CAFindResource(buf, token, tokenLength);
+    if (CA_STATUS_OK != res)
     {
-        printf("find resource error!!\n");
+        printf("Find resource error : %d\n", res);
+        CADestroyToken(token);
     }
     else
     {
-        printf("find resource to %s URI\n", buf);
-
-        gLastRequestToken = token;
+        printf("Find resource to %s URI\n", buf);
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
     }
 
-    // delete token
-    /*
-     if (token != NULL)
-     {
-     CADestroyToken(token);
-     }
-     */
-
     printf("=============================================\n");
 }
 
 void send_request()
 {
-    char secureRequest[2] = {0};
-    CAResult_t res;
-
-    res = get_network_type();
-    if (res != CA_STATUS_OK)
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
     {
         return;
     }
 
     printf("Do you want to send secure request ?.... enter (0/1): ");
-    gets(secureRequest);
-    if ('1' == secureRequest[0])
+
+    char secureRequest[MAX_BUF_LEN] = {0};
+    if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    if (strcmp(secureRequest, "1") == 0)
     {
         printf("Enter the URI like below....\n");
         printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
     }
-    else
+    else if (strcmp(secureRequest, "0") == 0)
     {
         printf("Enter the URI like below....\n");
         printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
         printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
     }
+    else
+    {
+        printf("Input data is wrong value\n");
+        return;
+    }
 
     char uri[MAX_BUF_LEN] = {'\0'};
-    gets(uri);
+    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
+    {
+        return;
+    }
 
     // create remote endpoint
     CARemoteEndpoint_t *endpoint = NULL;
-    if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, gSelectedNwType, &endpoint)
-        || !endpoint)
+    res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res || !endpoint)
     {
-        printf("Failed to create remote endpoint!\n");
-        CADestroyRemoteEndpoint(endpoint);
+        printf("Failed to create remote endpoint, error code : %d\n", res);
         return;
     }
 
-    //endpoint->connectivityType = gSelectedNwType;
-
-    char buf[MAX_BUF_LEN];
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
     printf("\n=============================================\n");
     printf("0:CON, 1:NON\n");
     printf("select message type : ");
 
-    gets(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
 
-    CAMessageType_t msgType = (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0;
+    CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
 
     // create token
     CAToken_t token = NULL;
-    if (CA_STATUS_OK != CAGenerateToken(&token))
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!\n");
-        token = NULL;
+        printf("Token generate error, error code : %d\n", res);
+        CADestroyRemoteEndpoint(endpoint);
+        return;
     }
 
-    printf("generated token %s\n", (token != NULL) ? token : "");
+    printf("Generated token %s\n", token);
 
     // extract relative resourceuri from give uri
-    char resourceURI[15] = {0};
-
     printf("URI : %s\n", uri);
-    get_resource_uri(uri, resourceURI, 14);
+
+    char resourceURI[15] = {0};
+    get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
 
     // create request data
-    CAInfo_t requestData;
-    memset(&requestData, 0, sizeof(CAInfo_t));
+    CAInfo_t requestData = { 0 };
     requestData.token = token;
-    if ('1' == secureRequest[0])
+    requestData.tokenLength = tokenLength;
+
+    if (strcmp(secureRequest, "1") == 0)
     {
-        int length = strlen(gSecureInfoData) + strlen(resourceURI) + 1;
-        requestData.payload = (CAPayload_t) malloc(length);
-        sprintf(requestData.payload, gSecureInfoData, resourceURI, gLocalSecurePort);
+        uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
+        if (NULL == requestData.payload)
+        {
+            printf("Memory allocation fail\n");
+            CADestroyRemoteEndpoint(endpoint);
+            CADestroyToken(token);
+            return;
+        }
+        snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
     }
     else
     {
-        int length = strlen(gNormalInfoData) + strlen(resourceURI) + 1;
-        requestData.payload = (CAPayload_t) malloc(length);
-        sprintf(requestData.payload, gNormalInfoData, resourceURI);
+        uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+        if (NULL == requestData.payload)
+        {
+            printf("Memory allocation fail\n");
+            CADestroyRemoteEndpoint(endpoint);
+            CADestroyToken(token);
+            return;
+        }
+        snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
     }
     requestData.type = msgType;
 
-    CARequestInfo_t requestInfo;
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+    CARequestInfo_t requestInfo = { 0 };
     requestInfo.method = CA_GET;
     requestInfo.info = requestData;
 
     // send request
-    CASendRequest(endpoint, &requestInfo);
-
-    if (token != NULL)
+    res = CASendRequest(endpoint, &requestInfo);
+    if (CA_STATUS_OK != res)
     {
-        CADestroyToken(token);
+        printf("Could not send request : %d\n", res);
     }
 
+    //destroy token
+    CADestroyToken(token);
     // destroy remote endpoint
     CADestroyRemoteEndpoint(endpoint);
+    free(requestData.payload);
+
+
     printf("=============================================\n");
 }
 
 void send_request_all()
 {
-    char buf[MAX_BUF_LEN];
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
-    CAResult_t res;
-
-    res = get_network_type();
-    if (res != CA_STATUS_OK)
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
     {
         return;
     }
 
     printf("\n=============================================\n");
-    printf("10.11.12.13:4545/resource_uri ( for IP )\n");
-    printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
-    printf("uri : ");
+    printf("ex) /a/light\n");
+    printf("resource uri : ");
 
-    gets(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
 
     // create remote endpoint
     CARemoteEndpoint_t *endpoint = NULL;
-    res = CACreateRemoteEndpoint(buf, gSelectedNwType, &endpoint);
+    res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Create remote endpoint error, error code: %d\n", res);
+        return;
+    }
 
-    if (res != CA_STATUS_OK)
+    CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+    if (NULL == group)
     {
-        printf("create remote endpoint error!!\n");
+        printf("Memory allocation failed!\n");
         CADestroyRemoteEndpoint(endpoint);
         return;
     }
-
-
-    CAGroupEndpoint_t *group = NULL;
-    group = (CAGroupEndpoint_t *)malloc(sizeof(CAGroupEndpoint_t));
-    group->connectivityType = endpoint->connectivityType;
+    group->transportType = endpoint->transportType;
     group->resourceUri = endpoint->resourceUri;
 
-
     // create token
     CAToken_t token = NULL;
-    res = CAGenerateToken(&token);
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
 
-    if (res != CA_STATUS_OK)
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!\n");
-        token = NULL;
+        printf("Token generate error!!\n");
+        CADestroyRemoteEndpoint(endpoint);
+        free(group);
+        return;
     }
 
-    printf("generated token %s\n", (token != NULL) ? token : "");
+    printf("generated token %s\n", token);
 
-    CAInfo_t requestData;
-    memset(&requestData, 0, sizeof(CAInfo_t));
+    CAInfo_t requestData = {CA_MSG_RESET};
     requestData.token = token;
+    requestData.tokenLength = tokenLength;
     requestData.payload = "Temp Json Payload";
     requestData.type = CA_MSG_NONCONFIRM;
-    CARequestInfo_t requestInfo;
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+
+    CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
     requestInfo.method = CA_GET;
     requestInfo.info = requestData;
 
-    // send request
-    // CASendRequest(endpoint, &requestInfo);
-    CASendRequestToAll(group, &requestInfo);
-
-    if (token != NULL)
+    // send request all
+    res = CASendRequestToAll(group, &requestInfo);
+    if (CA_STATUS_OK != res)
     {
+        printf("Could not send request to all\n");
         CADestroyToken(token);
     }
+    else
+    {
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
+    }
 
     // destroy remote endpoint
     CADestroyRemoteEndpoint(endpoint);
-
     free(group);
 
     printf("=============================================\n");
 }
 
-void advertise_resource()
+void send_notification()
 {
-    char buf[MAX_BUF_LEN];
-
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
 
     printf("\n=============================================\n");
+    printf("Enter the URI like below....\n");
+    printf("10.11.12.13:4545/resource_uri ( for IP )\n");
+    printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
     printf("uri : ");
 
-    scanf("%s", buf);
-
-    int optionNum = 0;
-    char optionData[MAX_OPT_LEN];
-
-    printf("Option Num : ");
-    scanf("%d", &optionNum);
-    CAHeaderOption_t *headerOpt;
-    headerOpt = (CAHeaderOption_t *) malloc(sizeof(CAHeaderOption_t) * optionNum);
-    if (NULL == headerOpt)
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("Memory allocation failed!\n");
         return;
     }
-    memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
-
-    int i;
-    for (i = 0 ; i < optionNum ; i++)
-    {
-        int optionID = 0;
-        printf("[%d] Option ID : ", i + 1);
-        scanf("%d", &optionID);
-        headerOpt[i].optionID = optionID;
 
-        memset(optionData, 0, sizeof(char) * MAX_OPT_LEN);
-        printf("[%d] Option Data : ", i + 1);
-        scanf("%s", optionData);
-        memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
-        printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData );
-
-        headerOpt[i].optionLength = (uint16_t)strlen(optionData);
-    }
     printf("\n=============================================\n");
+    printf("\tselect message type\n");
+    printf("CON     : 0\n");
+    printf("NON     : 1\n");
+    printf("select : ");
 
-    // create token
-    CAToken_t token = NULL;
-    CAResult_t res = CAGenerateToken(&token);
-    if (res != CA_STATUS_OK)
+    char messageTypeBuf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
     {
-        printf("token generate error!!\n");
-        token = NULL;
+        return;
     }
 
-    printf("generated token %s\n", (token != NULL) ? token : "");
-
-    CAAdvertiseResource(buf, token, headerOpt, (uint8_t)optionNum);
-
-    free(headerOpt);
-
-}
-
-void send_notification()
-{
-    char buf[MAX_BUF_LEN];
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
-    CAResult_t res;
+    int messageType = messageTypeBuf[0] - '0';
 
-    res = get_network_type();
-    if (res != CA_STATUS_OK)
+    switch(messageType)
     {
-        return;
+        case 0:
+                printf("CONFIRM messagetype is selected\n");
+                break;
+        case 1:
+                printf("NONCONFIRM messagetype is selected\n");
+                break;
+        default:
+                printf("Invalid Selection\n");
+                return;
     }
 
-    printf("\n=============================================\n");
-    printf("10.11.12.13:4545/resource_uri ( for IP )\n");
-    printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
-    printf("uri : ");
-
-    gets(buf);
-
     // create remote endpoint
     CARemoteEndpoint_t *endpoint = NULL;
-    res = CACreateRemoteEndpoint(buf, gSelectedNwType, &endpoint);
+    res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Create remote endpoint error, error code: %d\n", res);
+        return;
+    }
 
-    if (res != CA_STATUS_OK)
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("create remote endpoint error!!\n");
+        printf("Token generate error!!\n");
         CADestroyRemoteEndpoint(endpoint);
         return;
     }
 
-    CAInfo_t respondeData;
-    memset(&respondeData, 0, sizeof(CAInfo_t));
-    respondeData.token = "client token";
-    respondeData.payload = "Temp Notification Data";
+    printf("Generated token %s\n", token);
 
-    CAResponseInfo_t responseInfo;
-    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+    CAInfo_t respondData = { 0 };
+    respondData.token = token;
+    respondData.tokenLength = tokenLength;
+    respondData.payload = "Temp Notification Data";
+    respondData.type = messageType;
+
+    CAResponseInfo_t responseInfo = { 0 };
     responseInfo.result = CA_SUCCESS;
-    responseInfo.info = respondeData;
+    responseInfo.info = respondData;
 
-    // send request
+    // send notification
     res = CASendNotification(endpoint, &responseInfo);
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("send notification error\n");
+        printf("Send notification error, error code: %d\n", res);
     }
     else
     {
-        printf("send notification success\n");
+        printf("Send notification success\n");
     }
 
+    // destroy token
+    CADestroyToken(token);
     // destroy remote endpoint
-    if (endpoint != NULL)
-    {
-        CADestroyRemoteEndpoint(endpoint);
-    }
+    CADestroyRemoteEndpoint(endpoint);
 
     printf("\n=============================================\n");
 }
+
 void select_network()
 {
-    char buf[MAX_BUF_LEN];
-
     printf("\n=============================================\n");
     printf("\tselect network\n");
-    printf("ETHERNET : 0\n");
-    printf("WIFI : 1\n");
+    printf("IPv4 : 0\n");
     printf("EDR : 2\n");
     printf("LE : 3\n");
     printf("select : ");
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-    gets(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
 
     int number = buf[0] - '0';
 
-    number = (number < 0 || number > 3) ? 0 : number;
+    if (number < 0 || number > 3)
+    {
+        printf("Invalid network type\n");
+        return;
+    }
 
     CAResult_t res = CASelectNetwork(1 << number);
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("select network error\n");
-        gSelectedNwType = 1 << number;
+        printf("Select network error\n");
+        g_selected_nw_type = 1 << number;
     }
     else
     {
-        printf("select network success\n");
+        printf("Select network success\n");
     }
 
     printf("=============================================\n");
@@ -755,43 +850,46 @@ void select_network()
 
 void unselect_network()
 {
-    char buf[MAX_BUF_LEN];
-
     printf("\n=============================================\n");
     printf("\tunselect enabled network\n");
-    printf("ETHERNET : 0\n");
-    printf("WIFI : 1\n");
+    printf("IPv4 : 0\n");
     printf("EDR : 2\n");
     printf("LE : 3\n");
     printf("select : ");
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-    gets(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
 
     int number = buf[0] - '0';
 
-    number = (number < 0 || number > 3) ? 1 : number;
+    if (number < 0 || number > 3)
+    {
+        printf("Invalid network type\n");
+        return;
+    }
 
     CAResult_t res = CAUnSelectNetwork(1 << number);
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("unselect network error\n");
+        printf("Unselect network error\n");
     }
     else
     {
-        printf("unselect network success\n");
+        printf("Unselect network success\n");
     }
+
     printf("=============================================\n");
 }
 
 char get_menu()
 {
-    char buf[MAX_BUF_LEN];
-
     printf("\n=============================================\n");
     printf("\t\tMenu\n");
     printf("\ts : start server\n");
-    printf("\tD : start client\n");
+    printf("\tc : start client\n");
     printf("\tf : find resource\n");
     printf("\tr : send request\n");
     printf("\tt : send request to all\n");
@@ -803,105 +901,106 @@ char get_menu()
     printf("\th : handle request response\n");
     printf("\ty : run static client\n");
     printf("\tz : run static server\n");
+    printf("\tw : send secure request\n");
     printf("\tq : quit\n");
     printf("=============================================\n");
     printf("select : ");
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
-    gets(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        printf("Failed to get input data\n");
+    }
 
     return buf[0];
 }
 
 void handle_request_response()
 {
-    printf("handle_request_response\n");
+    printf("Handle_request_response\n");
 
     CAResult_t res = CAHandleRequestResponse();
-    if (res != CA_STATUS_OK)
+    if (CA_STATUS_OK != res)
     {
-        printf("handle request error\n");
+        printf("Handle request error, error code: %d\n", res);
     }
     else
     {
-        printf("handle request success\n");
+        printf("Handle request success\n");
     }
 }
 
 void get_network_info()
 {
-    int index;
-
-    CALocalConnectivity_t *tempInfo;
+    CALocalConnectivity_t *tempInfo = NULL;
     uint32_t tempSize = 0;
 
-    tempInfo = (CALocalConnectivity_t *) malloc(sizeof(CALocalConnectivity_t));
-
-    CAGetNetworkInformation(&tempInfo, &tempSize);
-    if (!tempSize)
+    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+    if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
     {
-        printf("network not connected\n");
+        printf("Network not connected\n");
+        free(tempInfo);
         return;
     }
 
     printf("################## Network Information #######################\n");
-    printf("network info total size is %d\n\n", tempSize);
+    printf("Network info total size is %d\n\n", tempSize);
+
+    int index;
     for (index = 0; index < tempSize; index++)
     {
-        if (tempInfo == NULL)
+        printf("Type: %d\n", tempInfo[index].type);
+        if (CA_IPV4 == tempInfo[index].type)
         {
-            break;
+            printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
+            printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
         }
-
-        printf("Type: %d\n", tempInfo->type);
-        printf("Address: %s\n", tempInfo->addressInfo.IP.ipAddress);
-        printf("Port: %d\n", tempInfo->addressInfo.IP.port);
-        printf("Secured: %d\n\n", tempInfo->isSecured);
-
-        if (CA_TRUE == tempInfo->isSecured)
+        else if (CA_EDR == tempInfo[index].type)
         {
-            gLocalSecurePort = tempInfo->addressInfo.IP.port;
+            printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
         }
-        else
+        printf("Secured: %d\n\n", tempInfo[index].isSecured);
+
+        if (tempInfo[index].isSecured)
         {
-            gLocalUnicastPort = tempInfo->addressInfo.IP.port;
+            g_local_secure_port = tempInfo[index].addressInfo.IP.port;
+            printf("Secured: in global %d\n\n", g_local_secure_port);
         }
-
-        tempInfo++;
     }
 
-    //free(tempInfo);
+    free(tempInfo);
     printf("##############################################################");
 }
 
 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
 {
-    if (!object)
+    if (NULL == object || NULL == requestInfo)
     {
-        printf("Remote endpoint is NULL!");
+        printf("Input parameter is NULL\n");
         return;
     }
 
-    if (!requestInfo)
+    if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
+        && (strncmp(g_last_request_token, requestInfo->info.token,
+                    requestInfo->info.tokenLength) == 0))
     {
-        printf("Request info is NULL!");
+        printf("Token is same. received request of it's own. skip.. \n");
         return;
     }
 
     printf("##########received request from remote device #############\n");
     printf("Uri: %s\n", object->resourceUri);
-    printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
-           object->addressInfo.IP.port, object->isSecured);
-
-    printf("Data: %s\n", requestInfo->info.payload);
-    printf("Message type: %s\n", gMessageType[requestInfo->info.type]);
-    if (gLastRequestToken != NULL && requestInfo->info.token != NULL
-        && (strcmp((char *)gLastRequestToken, requestInfo->info.token) == 0))
+    if (CA_IPV4 == object->transportType)
     {
-        printf("token is same. received request of it's own. skip.. \n");
-        return;
+        printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+               object->addressInfo.IP.port, object->isSecured);
+    }
+    else if (CA_EDR == object->transportType)
+    {
+        printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
     }
+    printf("Data: %s\n", requestInfo->info.payload);
+    printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
 
     if (requestInfo->info.options)
     {
@@ -918,57 +1017,66 @@ void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *re
     printf("############################################################\n");
 
     //Check if this has secure communication information
-    if (requestInfo->info.payload)
+    if (requestInfo->info.payload &&
+            (CA_IPV4 == object->transportType))
     {
         int securePort = get_secure_information(requestInfo->info.payload);
         if (0 < securePort) //Set the remote endpoint secure details and send response
         {
             printf("This is secure resource...\n");
-            char *uri = NULL;
-            int length = 0;
 
-            length = 8; //length of "coaps://"
-            length += strlen(object->addressInfo.IP.ipAddress) + 5; // length of "ipaddress:port"
+            //length of "coaps://"
+            int length = sizeof(SECURE_COAPS_PREFIX) - 1;
+
+            // length of "ipaddress:port"
+            length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
             length += strlen(object->resourceUri) + 1;
 
-            uri = calloc(1, sizeof(char) * length);
+            char *uri = calloc(1, sizeof(char) * length);
             if (!uri)
             {
                 printf("Failed to create new uri\n");
                 return;
             }
-            sprintf(uri, "coaps://%s:%d/%s", object->addressInfo.IP.ipAddress,
-                    securePort, object->resourceUri);
+            sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
+                    object->addressInfo.IP.port, object->resourceUri);
 
             CARemoteEndpoint_t *endpoint = NULL;
-            if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->connectivityType, &endpoint))
+            if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
             {
                 printf("Failed to create duplicate of remote endpoint!\n");
                 return;
             }
-            //endpoint->connectivityType = object->connectivityType;
-            endpoint->isSecured = CA_TRUE;
+            endpoint->isSecured = true;
             object = endpoint;
 
             free(uri);
         }
     }
 
-    printf("send response with URI\n");
+    printf("Send response with URI\n");
     send_response(object, &requestInfo->info);
 
-    gReceived = 1;
+    g_received = 1;
 }
 
 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
 {
     printf("##########Received response from remote device #############\n");
     printf("Uri: %s\n", object->resourceUri);
-    printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
-           object->addressInfo.IP.port, object->isSecured);
+    if (CA_IPV4 == object->transportType)
+    {
+        printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+               object->addressInfo.IP.port, object->isSecured);
+    }
+    else if (CA_EDR == object->transportType)
+    {
+        printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+    }
     printf("response result : %d\n", responseInfo->result);
     printf("Data: %s\n", responseInfo->info.payload);
-    printf("Message type: %s\n", gMessageType[responseInfo->info.type]);
+    printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
+    printf("Token: %s\n", responseInfo->info.token);
     if (responseInfo->info.options)
     {
         uint32_t len = responseInfo->info.numOptions;
@@ -982,7 +1090,7 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *
         }
     }
     printf("############################################################\n");
-    gReceived = 1;
+    g_received = 1;
 
     //Check if this has secure communication information
     if (responseInfo->info.payload)
@@ -995,79 +1103,156 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *
     }
 }
 
-void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
+void error_handler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
 {
-    printf("entering send_response\n");
+    printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
 
-    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.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.info = responseData;
-
-    if (CA_TRUE == endpoint->isSecured)
-        printf("Sending response on secure communication\n");
-    else
-        printf("Sending response on non-secure communication\n");
-
-    // send request (connectivityType from remoteEndpoint of request Info)
-    CAResult_t res = CASendResponse(endpoint, &responseInfo);
-    if (res != CA_STATUS_OK)
-{
-        printf("send response error\n");
+    if(rep && rep->resourceUri  )
+    {
+        printf("Error Handler, RemoteEndpoint Info resourceUri : %s\n", rep->resourceUri);
     }
     else
     {
-        printf("send response success\n");
+        printf("Error Handler, RemoteEndpoint is NULL");
     }
 
-    printf("=============================================\n");
+    if(errorInfo)
+    {
+        const CAInfo_t *info = &errorInfo->info;
+        printf("Error Handler, ErrorInfo :\n");
+        printf("Error Handler result    : %d\n", errorInfo->result);
+        printf("Error Handler token     : %s\n", info->token);
+        printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
+        printf("Error Handler type      : %d\n", info->type);
+        printf("Error Handler payload   : %s\n", info->payload);
+
+        if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
+        {
+            printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
+        }
+        else if(CA_SEND_FAILED == errorInfo->result)
+        {
+            printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
+        }
+        else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
+        {
+            printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
+        }
+        else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
+        {
+            printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
+        }
+        else if(CA_STATUS_FAILED == errorInfo->result)
+        {
+            printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
+        }
+    }
+    printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
+
+    return;
 }
 
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token)
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
 {
+    printf("entering send_response\n");
 
     printf("\n=============================================\n");
+    printf("\tselect message type\n");
+    printf("CON     : 0\n");
+    printf("NON     : 1\n");
+    printf("ACK     : 2\n");
+    printf("RESET   : 3\n");
+    printf("select : ");
 
-    CAInfo_t requestData;
-    memset(&requestData, 0, sizeof(CAInfo_t));
-    requestData.token = token;
-    requestData.payload = "Temp Json Payload";
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
 
-    CARequestInfo_t requestInfo;
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
+    int messageType = buf[0] - '0';
+    int responseCode = 0 ;
+    char responseCodeBuf[MAX_BUF_LEN] = { 0 };
+    if (CA_MSG_RESET != messageType)
+    {
+        printf("\n=============================================\n");
+        printf("\tselect response code\n");
+        printf("EMPTY                    :   0\n");
+        printf("SUCCESS                  : 200\n");
+        printf("CREATED                  : 201\n");
+        printf("DELETED                  : 202\n");
+        printf("BAD_REQ                  : 400\n");
+        printf("BAD_OPT                  : 402\n");
+        printf("NOT_FOUND                : 404\n");
+        printf("INTERNAL_SERVER_ERROR    : 500\n");
+        printf("RETRANSMIT_TIMEOUT       : 504\n");
+        printf("select : ");
+
+        if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
+        {
+            return;
+        }
+        responseCode = atoi(responseCodeBuf);
+    }
+    CAInfo_t responseData = { 0 };
+    responseData.type = messageType;
 
-    // send request
-    endpoint->connectivityType = CA_WIFI;
+    responseData.messageId = (info != NULL) ? info->messageId : 0;
+    if(CA_MSG_RESET != messageType)
+    {
+        responseData.token = (info != NULL) ? info->token : NULL;
+        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
 
-    CAResult_t res = CASendRequest(endpoint, &requestInfo);
-    if (res != CA_STATUS_OK)
+        if (endpoint->isSecured)
+        {
+            printf("Sending response on secure communication\n");
+
+            uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
+            responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
+            if (NULL == responseData.payload)
+            {
+                printf("Memory allocation fail\n");
+                return;
+            }
+            snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
+                     g_local_secure_port);
+        }
+        else
+        {
+            printf("Sending response on non-secure communication\n");
+
+            uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
+            responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
+            if (NULL == responseData.payload)
+            {
+                printf("Memory allocation fail\n");
+                return;
+            }
+            snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
+        }
+    }
+
+    CAResponseInfo_t responseInfo = { 0 };
+    responseInfo.result = responseCode;
+    responseInfo.info = responseData;
+
+    // send response (transportType from remoteEndpoint of request Info)
+    CAResult_t res = CASendResponse(endpoint, &responseInfo);
+    if (CA_STATUS_OK != res)
     {
-        printf("send request error\n");
+        printf("Send response error\n");
     }
     else
     {
-        printf("send request success\n");
+        printf("Send response success\n");
     }
 
     printf("=============================================\n");
-
 }
 
 int get_secure_information(CAPayload_t payLoad)
 {
-    printf("entering get_secure_information\n");
+    printf("Entering get_secure_information\n");
 
     if (!payLoad)
     {
@@ -1102,6 +1287,12 @@ int get_secure_information(CAPayload_t payLoad)
         return -1;
     }
 
+    if(((endPos - 1) - startPos) > 4)
+    {
+        printf("port length is not proper.Exceeding length 4\n");
+        return -1;
+    }
+
     char portStr[4] = {0};
     memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
 
@@ -1131,56 +1322,69 @@ void get_resource_uri(char *URI, char *resourceURI, int length)
     endPos -= 1;
 
     if (endPos - startPos <= length)
+    {
         memcpy(resourceURI, startPos + 1, endPos - startPos);
+    }
 
     printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
 }
 
 CAResult_t get_network_type()
 {
-    char buf[MAX_BUF_LEN];
-
     printf("\n=============================================\n");
     printf("\tselect network type\n");
-    printf("ETHERNET : 0\n");
-    printf("WIFI : 1\n");
-    printf("EDR : 2\n");
+    printf("IPv4 : 0\n");
+    printf("BT : 2\n");
     printf("LE : 3\n");
     printf("select : ");
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-    gets(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return CA_NOT_SUPPORTED ;
+    }
 
     int number = buf[0] - '0';
-
     number = (number < 0 || number > 3) ? 0 : 1 << number;
 
     if (!(number & 0xf))
     {
         return CA_NOT_SUPPORTED;
     }
-    if (number & CA_ETHERNET)
-    {
-        gSelectedNwType = CA_ETHERNET;
-        return CA_STATUS_OK;
-    }
-    if (number & CA_WIFI)
+    if (number & CA_IPV4)
     {
-        gSelectedNwType = CA_WIFI;
+        g_selected_nw_type = CA_IPV4;
         return CA_STATUS_OK;
     }
     if (number & CA_EDR)
     {
-        gSelectedNwType = CA_EDR;
+        g_selected_nw_type = CA_EDR;
         return CA_STATUS_OK;
     }
     if (number & CA_LE)
     {
-        gSelectedNwType = CA_LE;
+        g_selected_nw_type = CA_LE;
         return CA_STATUS_OK;
     }
 
     printf("\n=============================================\n");
-    return CA_STATUS_OK;
+
+    return CA_STATUS_FAILED;
 }
 
+CAResult_t get_input_data(char *buf, int32_t length)
+{
+    if (!fgets(buf, length, stdin))
+    {
+        printf("fgets error\n");
+        return CA_STATUS_FAILED;
+    }
+
+    char *p = NULL;
+    if ((p = strchr(buf, '\n')) != NULL)
+    {
+        *p = '\0';
+    }
+
+    return CA_STATUS_OK;
+}